Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load js Asynchronously But Execute Synchronously

The Scenario is that I have lots of js files. Different files are called depending on different platforms. So I have a question as I want to load files Asynchronously. But the Execution of these files should be done synchronously. Currently I am doing this function call

  function loadScriptJs(src) {   
     Console.log(' Call to file '+src);
     var file = document.createElement('script'),
            head = document.getElementsByTagName('head')[0];
    file.type = 'text/javascript';
    file.setAttribute("defer","defer");
    file.setAttribute("src",src);
    head.appendChild(file);
        file.onload = function() {            
              console.log(src + " is loaded.");
        };
  }

Now I have a array which has a list of js files being called. I loop through the array and call this function for each src. I have used document.ready function with in each of the js file. Here I have checked the dependencies of the files and made the sequence optimized. ie The dependent files are loaded later (come later in the array) and the more Parent like files come earlier.

Example:- If I have files A1,B2,C3,D4,E5 ..... like wise. My array is ['js/A1.js','js/B2.js','js/C3.js'...]. When I run this through the loop. I get the consoles of 'Call to file [filename]' is the same sequence as in the array but consoles of '[filename] is loaded' are not coming in the intended sequence.

Yes I cannot control the loading as its over the internet. But I want to the execution to be synchronous. ie Begin all file execution when the last file completes loading.

Can anyone provide me any advice, suggestion or idea for it.

like image 806
SSS Avatar asked May 28 '14 10:05

SSS


1 Answers

Dynamically inserted scripts may not adhere to the defer attribute. script tags have an async attribute. By default it's true. Explicitly set it to false.

file.setAttribute("async", "false");

or in plain HTML

<script type="text/javascript" async=false src="A1.js"></script>

You might also need to remove the document.ready method in each script and start the script's logic at the top level, appending each JS script to the bottom of the body tag instead of the header. If multiple scripts register for the ready event before it's fired you do not know what order they will be called in.

like image 191
Matt S Avatar answered Oct 23 '22 19:10

Matt S