External JavaScript Files And Execution Order

External JavaScript & Execution Order

In this tutorial Codingcompiler will explain the external JavaScript file and it’s execution order. Let’s start learning about asynchronous scripts in JavaScript and Async Vs Defer.

If there is a lot of JavaScript code, it is placed into a separate file that is connected in HTML:

<script src="/path/to/script.js"></script>

Here /path/to/script.jsis the absolute path to the file containing the script (from the site root).

The browser itself will download the script and execute.

You can also specify the full URL, for example:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js"></script>

You can also use the path relative to the current page. For example, it src="lodash.js"indicates a file from the current directory.

To connect multiple scripts, use multiple tags:

<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>
...

Note:

As a thumb rule, only the simplest scripts are written in HTML, and complex ones are put into a separate file.

The browser will only download it for the first time and, if the server is properly configured, it will be taken from its cache.

Due to this, the same large script, containing, for example, a library of functions, can be used on different pages without a complete reload from the server.If an attribute is specified src, the contents of the tag are ignored.

In one tag, SCRIPTyou can not simultaneously connect an external script and specify the code.

That’s not how it works:

           <script src="file.js">   alert(1); </script>

You need to choose: either SCRIPTcomes with srcor contains code. The tag above should be broken down into two: one with src, the other with code, like this:

<script src="file.js"></script>
<script>
  alert( 1 );
</script>

Asynchronous Scripts In JavaScript – Async Vs Defer

The browser loads and displays HTML gradually. This is especially noticeable with a slow Internet connection: the browser does not wait for the page to load as a whole, but shows the part that it managed to load.

If the browser sees the tag <script>, then it is obliged by the standard to execute it first, and then show the rest of the page.

For example, in the example below – until all the rabbits are counted – the bottom <p>one will not be shown:

 <!DOCTYPE HTML> 
<html> 
  <head>   
    <meta charset="utf-8"> 
  </head>
  <body>  
    <p>We start to count:</p>   
    <script>     alert( 'First rabbit!' ); alert( 'Second rabbit!' );     alert( 'Third rabbit!' );   </script>   
<p>Rabbits counted!</p> 
  </body>
</html>

This behavior is called “synchronous.” As a rule, it is quite normal, but there is an important consequence.

If the script is external, then until the browser executes it, it will not show part of the page below it.

That is, in such a document, until it loads and is executed big.js, the content <body>will be hidden:

 <html> 
  <head>
  <script src="big.js"></script>
  </head>
  <body> This text will not be displayed until the browser executes big.js. </body>
</html>

And here is the question – do we really want it? That is, is it really impossible to show the rest of the page before loading the script?

There are situations when we not only do not want such a delay, but it is even dangerous.

For example, if we include an external script that shows ads or inserts a visitor counter, and then our page goes. Of course, it’s wrong that until the counter or ad is loaded, the rest of the page is not shown. Visitor counter should not delay the display of the site page. Advertising also should not slow down the site and violate its functionality.

But what if the server from which the external script is loaded is overloaded? The visitor in this case can wait a very long time!

Here is an example, with a similar script (there is an artificial load delay):

<p>Important information will not appear until the script is loaded.</p>

<script src="https://js.cx/hello/ads.js?speed=0"></script>

<p>... Important information!</p>

What to do?

You can put all such scripts at the end of the page – this will reduce the problem, but will not get rid of it completely, if there are several scripts. Suppose at the end of page 3 of the script, and the first of them slows down – it turns out, the other two will wait for him – also not good.

In addition, the browser will reach the scripts located at the end of the page, they will start loading only when the whole page loads. And this is not always correct. For example, the visitor counter will most accurately work if you load it early.

Therefore, “positioning the scripts below” is not the best solution.

To fundamentally solve this problem will help attributes asyncor defer:Attribute async

Supported by all browsers except IE9-. The script runs completely asynchronously. That is, when detected, the <script async src="...">browser does not stop processing the page, but quietly works on. When the script is loaded – it will be executed.Attribute defer

Supported by all browsers, including the oldest IE. The script is also executed asynchronously, does not make the page wait, but there are two differences from async.

The first is that the browser ensures that the relative order of the scripts deferwill be preserved.

That is, in this code (c async), the script that first loads will work first:

<script src="1.js" async></script>
<script src="2.js" async></script>

And in this code (c defer), the first one will always work 1.js, and the script 2.js, even if loaded earlier, will wait for it.

<script src="1.js" defer></script>
<script src="2.js" defer></script>

Therefore, the attribute is deferused in cases where the second script 2.jsdepends on the first 1.js, for example, it uses something described by the first script.

The second difference is that the script deferwill work when the entire HTML document is processed by the browser.

For example, if the document is large enough …

<script src="async.js" async></script>
<script src="defer.js" defer></script>

Много много много букв

… That script async.jswill be executed as soon as it loads – perhaps before the whole document is ready. And defer.jswait for the readiness of the entire document.

This is convenient when we in the script want to work with the document, and must be sure that it is fully received.async together with defer

If specified simultaneously asyncdeferin modern browsers it will be used only async, in IE9- only defer(does not understand async).Attributes async/defer– for external scripts only

Attributes async/deferwork only if they are assigned to external scripts, i.e. having src.

If you try to assign them to regular scripts <script>…</script>, they will be ignored.

The same example with async:

              <p>It is no longer needed..</p> 
<script async src="https://js.cx/hello/ads.js?speed=0"></script>
<p>… Important information!</p>

At startup, you will see that the whole page is displayed right there, and alertfrom the external script will appear later when the script loads.These attributes have long been “in progress”

Most modern advertising systems and counters know about these attributes and use them.

Before inserting an external tag, an <script>understanding programmer will always check if he has a similar attribute. Otherwise, a slow script may delay page loading.Looking ahead

For an advanced reader who knows that tags <script>can be added to a page at any time using the javascript itself, we note that the scripts added in this way behave the same way as async. That is, they are executed as soon as they are loaded, without preserving the relative order.

If you want to keep the execution order, that is, add several scripts that will be executed strictly one after the other, then the property is used script.async = false.

It looks like this:

 function addScript(src){   var script = document.createElement('script');   script.src = src;   
script.async = false; // to guarantee order document.head.appendChild(script); }
addScript('1.js'); // these scripts will start loading right away
addScript('2.js'); // they are loaded
addScript('3.js'); // but guaranteed to be in order 1 -> 2 -> 3

In more detail, we will work on the page in the second part of the textbook.

Summery

  • Scripts are inserted into the page as text in a tag <script>, or as an external file through<script src="way"></script>
  • Specific attributes asyncand deferused to until loaded external script – the browser to show the rest (following it) of the page. Without them, this does not happen.
  • The difference between asyncand defer: the attribute deferpreserves the relative sequence of the scripts, but asyncnot. In addition, it deferalways waits until the entire HTML document is ready, but asyncnot.

It is very important not only to read the textbook, but to do something on your own.

Solve the problem to make sure you understand everything correctly.

Tasks to be performed:

Print alert with external script

Take the solution to the previous task. Output the alert and move the script to an external file alert.js, which is located in the same directory.

Open the page and check that the message is still working.decision

Which script will execute first?

In the example below, two scripts small.jsand are connected big.js.

If we assume that it small.jsloads much faster than big.js– which one will be executed first?

<script src="big.js"></script>
<script src="small.js"></script>

That’s how?

<script async src="big.js"></script>
<script async src="small.js"></script>

And so?

<script defer src="big.js"></script>
<script defer src="small.js"></script>

Related JavaScript Tutorials

JavaScript Tutorials For Beginners
Introduction to JavaScript
Javascript Reference and Specifications
Javascript Code editors
Javascript Developer Console

Leave a Comment