Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regarding sequence of control flow in html <script>

I have a html page like this:

<!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>

Could I assume the flow to be - download script 1 >> execute alert('hi1')>> download script2 >> execute alert('hi2') or is it browser specific - if yes, which browsers do what?

Thanks

like image 623
Tintin Avatar asked Dec 03 '13 22:12

Tintin


2 Answers

The browser will most likely download both scripts in parallel (unless either 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 a part of the script until the script is done loading and executes. This ensures you can safely include libraries in your code, and expect them to be present when the main script gets to run.

As has been noted, you shouldn't use script tags with both src and own content.

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

You can override this behavior by using the async or defer attributes.

async html5

Set this Boolean attribute to indicate that the browser should, if possible, execute the script asynchronously. It has no effect on inline scripts (i.e., scripts that don't have the src attribute).

defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute.

Neither attribute works in IE before IE 10, so don't rely on the script not executing in order anyways.

Compatibility table: async; defer

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

like image 66
John Dvorak Avatar answered Sep 21 '22 10:09

John Dvorak


Don't use <script> with both a src attribute and content between <script ...> and </script>. This can lead to unpredictable results. See this question and its answers.

like image 41
elixenide Avatar answered Sep 20 '22 10:09

elixenide