1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
|
---
title: জাভাস্ক্রিপ্ট কী?
slug: Learn/JavaScript/First_steps/জাভাস্ক্রিপ্ট-কী
translation_of: Learn/JavaScript/First_steps/What_is_JavaScript
---
<div>{{LearnSidebar}}</div>
<div>{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}</div>
<p class="summary">মোজিলা ডেভেলপার নেটওয়ার্ক এর প্রাথমিক জাভাস্ক্রিপ্ট এর কোর্সে স্বাগতাম! এই লেখায় আমরা জাভাস্ক্রিপ্টকে গভীরভাবে জানব, কিছু প্রশ্ন নিয়ে আলোচনা করব যেমন "জাভাস্ক্রিপ্ট কী" এবং "জাভাস্ক্রিপ্ট দিয়ে কী করা যায়?", সেই সাথে সহজভাবে কীভাবে জাভাস্ক্রিপ্ট ব্যবহার করতে সেটাও শিখব।</p>
<table class="learn-box standard-table">
<tbody>
<tr>
<th scope="row">আগে থেকে যা জানতে হবে</th>
<td>কম্পিউটার </td>
</tr>
<tr>
<th scope="row">উদ্দেশ্য:</th>
<td>জাভাস্ক্রিপ্ট এর সাথে পরিচিতি,</td>
</tr>
</tbody>
</table>
<h2 id="জাভস্ক্রিপ্ট_এর_পূর্ণাঙ্গ_সংজ্ঞা">জাভস্ক্রিপ্ট এর পূর্ণাঙ্গ সংজ্ঞা</h2>
<p>জাভাস্ক্রিপ্ট মূলত একটি scripting ভাষা বা programming ভাষা। জাভাস্ক্রিপ্ট ব্যবহার করে ওয়েবসাইটে জটিল বৈশিষ্ট্য যুক্ত করা যায় যেমন নির্দিষ্ট সময় অনু্যায়ী কনটেন্ট পরিবর্তন করা, মানচিত্র যোগ করা ওয়েবসাইটে 2D/3D animation যুক্ত করা ইত্যাদি। নিচের ওয়েব প্রযুক্তি রূপক যে কেক আছে সেটার তৃতীয় স্তর হচ্ছে জাভাস্ক্রিপ্ট। </p>
<p><img alt="" src="https://mdn.mozillademos.org/files/13502/cake.png" style="display: block; margin: 0 auto;"></p>
<ul>
<li>{{glossary("HTML")}} হচ্ছে মার্ক আপ ভাষা। এই ভাষা ব্যবহার করে ওয়েব সাইট তৈরী করা হয় এবং ওয়েবসাইটের কনটেন্ট এ অর্থবহ করা হয়। যেমন পেইজে প্যারগ্রাফ, শিরোনাম, ডাটা টেবি অথবা ছবি বা ভিডিও যুক্ত করা ইত্যাদি। </li>
<li>{{glossary("CSS")}} দিয়ে HTML এর কনটেন্ট এর সাথে স্টাইল যুক্ত করা হয় যাতে ওয়েবসাইট টা দৃষ্টিনন্দন হয়। যেমন ব্যাকগ্রাউন্ড এ রঙ যুক্ত করা, ফন্ট নিয়ে কাজ করা, ওয়েবসাইটের কলামকে বিভিন্ন কলামে ঠিক করা ইত্যাদি।</li>
<li>{{glossary("JavaScript")}} একটি scripting ভাষা। Scripting ভাষা হচ্ছে একটি প্রোগ্রামিং ভাষা যেটি interpreter ব্যবহার করে কোড রান করে। জাভাস্ক্রিপ্ট ব্যবহার করে সক্রিয়ভাবে কনটেন্ট পরিবর্তন, মাল্টিমিডিয়ার নিয়ন্ত্রণ, ছবির এনিমেশন, এবং আরও অনেক কাজ করা যায়। </li>
</ul>
<p>তিনটা পর্যায় একটি আরেকটির উপর সুন্দরভাবে তৈরি। উদাহরণস্বরূপ নিচের টেক্সটটিকে দেখা যাক। HTML ব্যবহার করে আমরা লেখাটিকে মার্ক আপ করবঃ </p>
<pre class="brush: html notranslate"><p>Player 1: Chris</p></pre>
<p><img alt="" src="https://mdn.mozillademos.org/files/13422/just-html.png" style="height: 28px; width: 108px;"></p>
<p>তারপর লেখাটিকে সুন্দর করার জন্য আমরা কিছু CSS যোগ করবঃ</p>
<pre class="brush: css notranslate">p {
font-family: 'helvetica neue', helvetica, sans-serif;
letter-spacing: 1px;
text-transform: uppercase;
text-align: center;
border: 2px solid rgba(0,0,200,0.6);
background: rgba(0,0,200,0.3);
color: rgba(0,0,200,0.6);
box-shadow: 1px 1px 2px rgba(0,0,200,0.4);
border-radius: 10px;
padding: 3px 10px;
display: inline-block;
cursor: pointer;
}</pre>
<p><img alt="" src="https://mdn.mozillademos.org/files/13424/html-and-css.png" style="height: 48px; width: 187px;"></p>
<p>এবং সবশেষে আমরা জাভাস্ক্রিপ্ট ব্যবহার করে কনটেন্ট যুক্ত করবঃ </p>
<pre class="brush: js notranslate">const para = document.querySelector('p');
para.addEventListener('click', updateName);
function updateName() {
let name = prompt('Enter a new name');
para.textContent = 'Player 1: ' + name;
}
</pre>
<p>{{ EmbedLiveSample('A_high-level_definition', '100%', 80, "", "", "hide-codepen-jsfiddle") }}</p>
<p>কী ঘটছে তা দেখার জন্য লেখাটির সর্বশেষ সংস্করনে ক্লিক করে দেখুন (উল্লেখ্য আপনি এই ডেমোটা GitHub এও পাবেন — <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/javascript-label.html">সোর্স কোড দেখুন</a>, অথবা <a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/javascript-label.html"> সরাসরি চালিয়ে দেখুন </a>)!</p>
<p>জাভাস্ক্রিপ্ট আরো অনেক কিছু করতে পারে - বিস্তারিত জেনে নেওয়া যাক। </p>
<h2 id="জাভাস্ক্রিপ্ট_প্রকৃতভাবে_কী_কী_করতে_পারে">জাভাস্ক্রিপ্ট প্রকৃতভাবে কী কী করতে পারে? </h2>
<p>মূল client-side জাভাস্ক্রিপ্ট সাধারণ কিছু প্রোগ্রামিং বৈশিষ্ট্য নিয়ে তৈরি যা দিয়ে আপনি নিচের </p>
<ul>
<li>Store useful values inside variables. In the above example for instance, we ask for a new name to be entered then store that name in a variable called <code>name</code>.</li>
<li>Operations on pieces of text (known as "strings" in programming). In the above example we take the string "Player 1: " and join it to the <code>name</code> variable to create the complete text label, e.g. ''Player 1: Chris".</li>
<li>Running code in response to certain events occurring on a web page. We used a {{Event("click")}} event in our example above to detect when the button is clicked and then run the code that updates the text label.</li>
<li>And much more!</li>
</ul>
<p>What is even more exciting however is the functionality built on top of the client-side JavaScript language. So-called <strong>Application Programming Interfaces</strong> (<strong>APIs</strong>) provide you with extra superpowers to use in your JavaScript code.</p>
<p>APIs are ready-made sets of code building blocks that allow a developer to implement programs that would otherwise be hard or impossible to implement. They do the same thing for programming that ready-made furniture kits do for home building — it is much easier to take ready-cut panels and screw them together to make a bookshelf than it is to work out the design yourself, go and find the correct wood, cut all the panels to the right size and shape, find the correct-sized screws, and <em>then</em> put them together to make a bookshelf.</p>
<p>They generally fall into two categories.</p>
<p><img alt="" src="https://mdn.mozillademos.org/files/13508/browser.png" style="display: block; height: 511px; margin: 0px auto; width: 815px;"></p>
<p><strong>Browser APIs</strong> are built into your web browser, and are able to expose data from the surrounding computer environment, or do useful complex things. For example:</p>
<ul>
<li>The {{domxref("Document_Object_Model","DOM (Document Object Model) API")}} allows you to manipulate HTML and CSS, creating, removing and changing HTML, dynamically applying new styles to your page, etc. Every time you see a popup window appear on a page, or some new content displayed (as we saw above in our simple demo) for example, that's the DOM in action.</li>
<li>The {{domxref("Geolocation","Geolocation API")}} retrieves geographical information. This is how <a href="https://www.google.com/maps">Google Maps</a> is able to find your location and plot it on a map.</li>
<li>The {{domxref("Canvas_API","Canvas")}} and {{domxref("WebGL_API","WebGL")}} APIs allow you to create animated 2D and 3D graphics. People are doing some amazing things using these web technologies —see <a href="https://www.chromeexperiments.com">Chrome Experiments</a> and <a href="http://webglsamples.org/">webglsamples</a>.</li>
<li><a href="https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery">Audio and Video APIs</a> like {{domxref("HTMLMediaElement")}} and {{domxref("WebRTC API", "WebRTC")}} allow you to do really interesting things with multimedia, such as play audio and video right in a web page, or grab video from your web camera and display it on someone else's computer (try our simple <a href="http://chrisdavidmills.github.io/snapshot/">Snapshot demo</a> to get the idea).</li>
</ul>
<div class="note">
<p><strong>Note</strong>: Many of the above demos won't work in an older browser — when experimenting, it's a good idea to use a modern browser like Firefox, Chrome, Edge or Opera to run your code in. You will need to consider <a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing">cross browser testing</a> in more detail when you get closer to delivering production code (i.e. real code that real customers will use).</p>
</div>
<p><strong>Third party APIs</strong> are not built into the browser by default, and you generally have to grab their code and information from somewhere on the Web. For example:</p>
<ul>
<li>The <a href="https://dev.twitter.com/overview/documentation">Twitter API</a> allows you to do things like displaying your latest tweets on your website.</li>
<li>The <a href="https://developers.google.com/maps/">Google Maps API</a> and <a href="https://wiki.openstreetmap.org/wiki/API">OpenStreetMap API</a> allows you to embed custom maps into your website, and other such functionality.</li>
</ul>
<div class="note">
<p><strong>Note</strong>: These APIs are advanced, and we'll not be covering any of these in this module. You can find out much more about these in our <a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs">Client-side web APIs module</a>.</p>
</div>
<p>There's a lot more available, too! However, don't get over excited just yet. You won't be able to build the next Facebook, Google Maps, or Instagram after studying JavaScript for 24 hours — there are a lot of basics to cover first. And that's why you're here — let's move on!</p>
<h2 id="What_is_JavaScript_doing_on_your_page">What is JavaScript doing on your page?</h2>
<p>Here we'll actually start looking at some code, and while doing so, explore what actually happens when you run some JavaScript in your page.</p>
<p>Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our <a href="/en-US/Learn/CSS/Introduction_to_CSS/How_CSS_works#How_does_CSS_actually_work">How CSS works</a> article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).</p>
<p><img alt="" src="https://mdn.mozillademos.org/files/13504/execution.png" style="display: block; margin: 0 auto;"></p>
<p>A very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above). Note that the code in your web documents is generally loaded and executed in the order it appears on the page. If the JavaScript loads and tries to run before the HTML and CSS it is affecting has been loaded, errors can occur. You will learn ways around this later in the article, in the <a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#Script_loading_strategies">Script loading strategies</a> section.</p>
<h3 id="Browser_security">Browser security</h3>
<p>Each browser tab has its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. This is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.</p>
<div class="note">
<p><strong>Note</strong>: There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.</p>
</div>
<h3 id="JavaScript_running_order">JavaScript running order</h3>
<p>When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. For example, let's return to the block of JavaScript we saw in our first example:</p>
<pre class="brush: js notranslate">const para = document.querySelector('p');
para.addEventListener('click', updateName);
function updateName() {
let name = prompt('Enter a new name');
para.textContent = 'Player 1: ' + name;
}</pre>
<p>Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the <code>updateName()</code> code block (lines 5–8) is run. The <code>updateName()</code> code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display.</p>
<p>If you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer console</a> — <code>TypeError: para is undefined</code>. This means that the <code>para</code> object does not exist yet, so we can't add an event listener to it.</p>
<div class="note">
<p><strong>Note</strong>: This is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them.</p>
</div>
<h3 id="Interpreted_versus_compiled_code">Interpreted versus compiled code</h3>
<p>You might hear the terms <strong>interpreted</strong> and <strong>compiled</strong> in the context of programming. In interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it. The code is received in its programmer-friendly text form and processed directly from that.</p>
<p>Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer. For example, C/C++ are compiled into machine code that is then run by the computer. The program is executed from a binary format, which was generated from the original program source code.</p>
<p>JavaScript is a lightweight interpreted programming language. The web browser receives the JavaScript code in its original text form and runs the script from that. From a technical standpoint, most modern JavaScript interpreters actually use a technique called <strong>just-in-time compiling</strong> to improve performance; the JavaScript source code gets compiled into a faster, binary format while the script is being used, so that it can be run as quickly as possible. However, JavaScript is still considered an interpreted language, since the compilation is handled at run time, rather than ahead of time.</p>
<p>There are advantages to both types of language, but we won't discuss them right now.</p>
<h3 id="Server-side_versus_client-side_code">Server-side versus client-side code</h3>
<p>You might also hear the terms <strong>server-side</strong> and <strong>client-side</strong> code, especially in the context of web development. Client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser. In this module we are explicitly talking about <strong>client-side JavaScript</strong>.</p>
<p>Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser. Examples of popular server-side web languages include PHP, Python, Ruby, ASP.NET and... JavaScript! JavaScript can also be used as a server-side language, for example in the popular Node.js environment — you can find out more about server-side JavaScript in our <a href="/en-US/docs/Learn/Server-side">Dynamic Websites – Server-side programming</a> topic.</p>
<h3 id="Dynamic_versus_static_code">Dynamic versus static code</h3>
<p>The word <strong>dynamic</strong> is used to describe both client-side JavaScript, and server-side languages — it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required. Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, filling it with data requested from the server, then displaying the table in a web page shown to the user. The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.</p>
<p>A web page with no dynamically updating content is referred to as <strong>static</strong> — it just shows the same content all the time.</p>
<h2 id="How_do_you_add_JavaScript_to_your_page">How do you add JavaScript to your page?</h2>
<p>JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses {{htmlelement("link")}} elements to apply external stylesheets and {{htmlelement("style")}} elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the {{htmlelement("script")}} element. Let's learn how this works.</p>
<h3 id="Internal_JavaScript">Internal JavaScript</h3>
<ol>
<li>First of all, make a local copy of our example file <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/apply-javascript.html">apply-javascript.html</a>. Save it in a directory somewhere sensible.</li>
<li>Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.</li>
<li>Next, go to your text editor and add the following in your head — just before your closing <code></head></code> tag:
<pre class="brush: html notranslate"><script>
// JavaScript goes here
</script></pre>
</li>
<li>Now we'll add some JavaScript inside our {{htmlelement("script")}} element to make the page do something more interesting — add the following code just below the "// JavaScript goes here" line:
<pre class="brush: js notranslate">document.addEventListener("DOMContentLoaded", function() {
function createParagraph() {
let para = document.createElement('p');
para.textContent = 'You clicked the button!';
document.body.appendChild(para);
}
const buttons = document.querySelectorAll('button');
for(let i = 0; i < buttons.length ; i++) {
buttons[i].addEventListener('click', createParagraph);
}
});</pre>
</li>
<li>Save your file and refresh the browser — now you should see that when you click the button, a new paragraph is generated and placed below.</li>
</ol>
<div class="note">
<p><strong>Note</strong>: If your example doesn't seem to work, go through the steps again and check that you did everything right. Did you save your local copy of the starting code as a <code>.html</code> file? Did you add your {{htmlelement("script")}} element just before the <code></head></code> tag? Did you enter the JavaScript exactly as shown? <strong>JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.</strong></p>
</div>
<div class="note">
<p><strong>Note</strong>: You can see this version on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/apply-javascript-internal.html">apply-javascript-internal.html</a> (<a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/apply-javascript-internal.html">see it live too</a>).</p>
</div>
<h3 id="External_JavaScript">External JavaScript</h3>
<p>This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.</p>
<ol>
<li>First, create a new file in the same directory as your sample HTML file. Call it <code>script.js</code> — make sure it has that .js filename extension, as that's how it is recognized as JavaScript.</li>
<li>Replace your current {{htmlelement("script")}} element with the following:
<pre class="brush: html notranslate"><script src="script.js" defer></script></pre>
</li>
<li>Inside <code>script.js</code>, add the following script:
<pre class="brush: js notranslate">function createParagraph() {
let para = document.createElement('p');
para.textContent = 'You clicked the button!';
document.body.appendChild(para);
}
const buttons = document.querySelectorAll('button');
for(let i = 0; i < buttons.length ; i++) {
buttons[i].addEventListener('click', createParagraph);
}</pre>
</li>
<li>Save and refresh your browser, and you should see the same thing! It works just the same, but now we've got our JavaScript in an external file. This is generally a good thing in terms of organizing your code and making it reusable across multiple HTML files. Plus, the HTML is easier to read without huge chunks of script dumped in it.</li>
</ol>
<div class="note">
<p><strong>Note</strong>: You can see this version on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/apply-javascript-external.html">apply-javascript-external.html</a> and <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/script.js">script.js</a> (<a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/apply-javascript-external.html">see it live too</a>).</p>
</div>
<h3 id="Inline_JavaScript_handlers">Inline JavaScript handlers</h3>
<p>Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might look something like this:</p>
<div id="inline_js_example">
<pre class="brush: js example-bad notranslate">function createParagraph() {
let para = document.createElement('p');
para.textContent = 'You clicked the button!';
document.body.appendChild(para);
}</pre>
<pre class="brush: html example-bad notranslate"><button onclick="createParagraph()">Click me!</button></pre>
</div>
<p>You can try this version of our demo below.</p>
<p>{{ EmbedLiveSample('inline_js_example', '100%', 150, "", "", "hide-codepen-jsfiddle") }}</p>
<p>This demo has exactly the same functionality as in the previous two sections, except that the {{htmlelement("button")}} element includes an inline <code>onclick</code> handler to make the function run when the button is pressed.</p>
<p><strong>Please don't do this, however.</strong> It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the <code>onclick="createParagraph()"</code> attribute on every button you want the JavaScript to apply to.</p>
<p>Using a pure JavaScript construct allows you to select all the buttons using one instruction. The code we used above to serve this purpose looks like this:</p>
<pre class="brush: js notranslate">const buttons = document.querySelectorAll('button');
for(let i = 0; i < buttons.length ; i++) {
buttons[i].addEventListener('click', createParagraph);
}</pre>
<p>This might be a bit longer than the <code>onclick</code> attribute, but it will work for all buttons — no matter how many are on the page, nor how many are added or removed. The JavaScript does not need to be changed.</p>
<div class="note">
<p><strong>Note</strong>: Try editing your version of <code>apply-javascript.html</code> and add a few more buttons into the file. When you reload, you should find that all of the buttons when clicked will create a paragraph. Neat, huh?</p>
</div>
<h3 id="Script_loading_strategies">Script loading strategies</h3>
<p>There are a number of issues involved with getting scripts to load at the right time. Nothing is as simple as it seems! A common problem is that all the HTML on a page is loaded in the order in which it appears. If you are using JavaScript to manipulate elements on the page (or more accurately, the <a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents#The_document_object_model">Document Object Model</a>), your code won't work if the JavaScript is loaded and parsed before the HTML you are trying to do something to.</p>
<p>In the above code examples, in the internal and external examples the JavaScript is loaded and run in the head of the document, before the HTML body is parsed. This could cause an error, so we've used some constructs to get around it.</p>
<p>In the internal example, you can see this structure around the code:</p>
<pre class="brush: js notranslate">document.addEventListener("DOMContentLoaded", function() {
...
});</pre>
<p>This is an event listener, which listens for the browser's "DOMContentLoaded" event, which signifies that the HTML body is completely loaded and parsed. The JavaScript inside this block will not run until after that event is fired, therefore the error is avoided (you'll <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">learn about events</a> later in the course).</p>
<p>In the external example, we use a more modern JavaScript feature to solve the problem, the <code>defer</code> attribute, which tells the browser to continue downloading the HTML content once the <code><script></code> tag element has been reached.</p>
<pre class="brush: js notranslate"><script src="script.js" defer></script></pre>
<p>In this case both the script and the HTML will load simultaneously and the code will work.</p>
<div class="note">
<p><strong>Note</strong>: In the external case, we did not need to use the <code>DOMContentLoaded</code> event because the <code>defer</code> attribute solved the problem for us. We didn't use the <code>defer</code> solution for the internal JavaScript example because <code>defer</code> only works for external scripts.</p>
</div>
<p>An old-fashioned solution to this problem used to be to put your script element right at the bottom of the body (e.g. just before the <code></body></code> tag), so that it would load after all the HTML has been parsed. The problem with this solution is that loading/parsing of the script is completely blocked until the HTML DOM has been loaded. On larger sites with lots of JavaScript, this can cause a major performance issue, slowing down your site.</p>
<h4 id="async_and_defer">async and defer</h4>
<p>There are actually two modern features we can use to bypass the problem of the blocking script — <code>async</code> and <code>defer</code> (which we saw above). Let's look at the difference between these two.</p>
<p>Scripts loaded using the <code>async</code> attribute (see below) will download the script without blocking rendering the page and will execute it as soon as the script finishes downloading. You get no guarantee that scripts will run in any specific order, only that they will not stop the rest of the page from displaying. It is best to use <code>async</code> when the scripts in the page run independently from each other and depend on no other script on the page.</p>
<p>For example, if you have the following script elements:</p>
<pre class="brush: html notranslate"><script async src="js/vendor/jquery.js"></script>
<script async src="js/script2.js"></script>
<script async src="js/script3.js"></script></pre>
<p>You can't rely on the order the scripts will load in. <code>jquery.js</code> may load before or after <code>script2.js</code> and <code>script3.js</code> and if this is the case, any functions in those scripts depending on <code>jquery</code> will produce an error because <code>jquery</code> will not be defined at the time the script runs.</p>
<p><code>async</code> should be used when you have a bunch of background scripts to load in, and you just want to get them in place asap. For example, maybe you have some game data files to load, which will be needed when the game actually begins, but for now you just want to get on with showing the game intro, titles, and lobby, without them being blocked by script loading.</p>
<p>Scripts loaded using the <code>defer</code> attribute (see below) will run in the order they appear in the page and execute them as soon as the script and content are downloaded:</p>
<pre class="brush: html notranslate"><script defer src="js/vendor/jquery.js"></script>
<script defer src="js/script2.js"></script>
<script defer src="js/script3.js"></script></pre>
<p>All the scripts with the <code>defer</code> attribute will load in the order they appear on the page. So in the second example, we can be sure that <code>jquery.js</code> will load before <code>script2.js</code> and <code>script3.js</code> and that <code>script2.js</code> will load before <code>script3.js</code>. They won't run until the page content has all loaded, which is useful if your scripts depend on the DOM being in place (e.g. they modify one of more elements on the page).</p>
<p>To summarize:</p>
<ul>
<li><code>async</code> and <code>defer</code> both instruct the browser to download the script(s) in a separate thread, while the rest of the page (the DOM, etc.) is downloading, so the page loading is not blocked by the scripts.</li>
<li>If your scripts should be run immediately and they don't have any dependencies, then use <code>async</code>.</li>
<li>If your scripts need to wait for parsing and depend on other scripts and/or the DOM being in place, load them using <code>defer</code> and put their corresponding <code><script></code> elements in the order you want the browser to execute them.</li>
</ul>
<h2 id="Comments">Comments</h2>
<p>As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist simply to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after six months and can't remember what you did). Comments are very useful, and you should use them often, particularly for larger applications. There are two types:</p>
<ul>
<li>A single line comment is written after a double forward slash (//), e.g.
<pre class="brush: js notranslate">// I am a comment</pre>
</li>
<li>A multi-line comment is written between the strings /* and */, e.g.
<pre class="brush: js notranslate">/*
I am also
a comment
*/</pre>
</li>
</ul>
<p>So for example, we could annotate our last demo's JavaScript with comments like so:</p>
<pre class="brush: js notranslate">// Function: creates a new paragraph and appends it to the bottom of the HTML body.
function createParagraph() {
let para = document.createElement('p');
para.textContent = 'You clicked the button!';
document.body.appendChild(para);
}
/*
1. Get references to all the buttons on the page in an array format.
2. Loop through all the buttons and add a click event listener to each one.
When any button is pressed, the createParagraph() function will be run.
*/
const buttons = document.querySelectorAll('button');
for (let i = 0; i < buttons.length ; i++) {
buttons[i].addEventListener('click', createParagraph);
}</pre>
<div class="note">
<p><strong>Note</strong>: In general more comments are usually better than less, but you should be careful if you find yourself adding lots of comments to explain what variables are (your variable names perhaps should be more intuitive), or to explain very simple operations (maybe your code is overcomplicated).</p>
</div>
<h2 id="Summary">Summary</h2>
<p>So there you go, your first step into the world of JavaScript. We've begun with just theory, to start getting you used to why you'd use JavaScript and what kind of things you can do with it. Along the way, you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.</p>
<p>JavaScript may seem a bit daunting right now, but don't worry — in this course, we will take you through it in simple steps that will make sense going forward. In the next article, we will <a href="/en-US/docs/Learn/JavaScript/Introduction_to_JavaScript_1/A_first_splash">plunge straight into the practical</a>, getting you to jump straight in and build your own JavaScript examples.</p>
<ul>
</ul>
<p>{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}</p>
<h2 id="In_this_module">In this module</h2>
<ul>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li>
</ul>
|