Regarding control flow sequence in html <script>

I have an html page:

<!DOCTYPE HTML> <html style="width: 100%; height: 100%"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style> </style> </head> <body style="height: 100%; width: 100%; margin: 0"> <div id="outerParentDiv" style="width:100%; height: 100%;"> </div> <script src="<script1 - takes very long to download>"> alert('hi1'); </script> <script src="<script2 - takes very short to download>"> alert('hi2'); </script> </body> </html> 

Is it possible to read the stream - load script 1 → execute warning ('hi1') → load script2 → execute alert ('hi2') or is it a browser specific - if so, which browsers do what?

thanks

+6
source share
3 answers

The browser will most likely load both scripts in parallel (unless the script is already cached), but the execution order is guaranteed to be in order. Moreover, the part of the page that is behind the script will not become part of the script until the script has loaded and executed. This ensures that you can safely include libraries in your code and expect them to be present when you run the main script.

As already noted, you should not use script tags with either src or your own content.

 <script src = "http://path.to.a.cdn/jquery-latest.min.js"></script> <script> $(function(){ ... }) </script> 

You can override this behavior using async or defer .

async

Set this boolean attribute to indicate that the browser should, if possible, execute the script asynchronously. It does not affect embedded scripts (i.e., scripts that do not have the src attribute).

Move

This Boolean attribute is set to indicate to the browser that the script is intended to be executed after the document has been parsed. Since this feature has not yet been implemented by all other major browsers, authors should not assume that script execution will actually be delayed. Never call document.write() with a defer script (since Gecko 1.9.2, this will deflate the document). The defer attribute should not be used for scripts that do not have the src attribute.

No attribute works in IE prior to IE 10, so don't rely on a script that doesn't execute anyway.

Compatibility Chart: async ; defer

Link: https://developer.mozilla.org/en/docs/Web/HTML/Element/script

+3
source

It is right. By default, the browser interprets the HTML source code in turn. However, some browser configurations may send multiple HTTP ( EDITED ) requests at the same time, but the execution order printed in your code is guaranteed.

+2
source

Do not use <script> with either the src attribute or the content between <script ...> and </script> . This can lead to unpredictable results. See this question and its answers .

+1
source

Source: https://habr.com/ru/post/959282/


All Articles