mercredi 24 mai 2017

How to force immediate javascript parsing / execution

The following is the outline of http://ift.tt/1cSsWBk

<html>
    <head>
      ..
      ..
    </head>
    <body>
        <script>
            var js1 = document.createElement('script');
            js1.type = "text/javascript";
            js1.async = true;
            js1.src = "cdn/js1.js";
            document.getElementsByTagName('head').appendChild(js1);
            console.log('Start: ' + new Date().getTime());
        </script>
        <img src="img1.jpg">
        <img src="img2.jpg">
        ....
    </body>
</html>

This is the contents of js1.js

console.log('End: ' + new Date().getTime());
var img = new Image();
img.src = "img3.jpg";

var f1 = function() {
..
}

var f2 = function() {
..
}

...

The observation is that there is a pretty large difference being observed between the 'End' and 'Start' outputs. In the browser network tab, I find that this is the order of network requests being made:

  1. js1.js
  2. img1.jpg
  3. img2.jpg
  4. img3.jpg

The question is - why does it take so long for the script to begin executing? I tried removing the other images from the page, this causes the script to execute much quicker. Why do the other requests execute before the script executes (I find this happens even if the call is made synchronously)? Is there a way to make the script execute completely first before the rest of the page does?




Aucun commentaire:

Enregistrer un commentaire