Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load javascript sequentially from javascript code

Tags:

javascript

I have a javascript widget that is included in a page by inserting a single script tag (as the application should be easiliy distributable):

<script type="text/javascript" src="loadMyWidget.js"></script>

loadMyWidget.js then needs to load multiple script files, which has to run in a certain sequence. I've tried to load them async by inserting script elements into the DOM, but that doesn't give me control of the sequence.

I also tried using head.js which is great for modern browsers, but I can't get it to work in IE7 and 8.

Minifying the scripts into one file is unfortunately difficult, as it is composed of a number of files from different projects and I wouldn't know when to update the script.

As simple as it seems, I need to load javascript files from javascript code in a certain sequence and get it to work in all browsers, including IE7 and 8.

like image 783
Jørgen Avatar asked May 31 '12 13:05

Jørgen


People also ask

What is the fastest way to load JavaScript?

Optimize Javascript Placement Place your javascript at the end of your HTML file if possible. Notice how Google analytics and other stat tracking software wants to be right before the closing </body> tag. This allows the majority of page content (like images, tables, text) to be loaded and rendered first.

Does JavaScript run code sequentially?

By default, JavaScript runs in a single process – in both web browsers and Node. js. The so-called event loop sequentially executes tasks (pieces of code) inside that process.


1 Answers

If you're using jQuery.getScript() you can use it as a $.when() to hold off execution until things have stopped loading.

If by "sequential execution" you mean that you need to load the requisites before execution the following will work

$(function(){
   $.when(
      $.getScript("/script1"),
      $.getScript("/scirpt2"),
      $.getScript("/script3")
}).done(function(){
    // do stuff with the contents of my new script files
});

If by sequential execution you mean that you need to execute files one after the other try this:

$.Deferred()
.then(function () { return $.getScript("/script1"); })
.then(function () { return $.getScript("/scirpt2"); })
.then(function () { return $.getScript("/script3"); })
.resolve();

Of course, this requires jQuery, which after your edits, this may not work for you.

Suggested Reading

  • http://api.jquery.com/jQuery.getScript
  • http://api.jquery.com/category/deferred-object/
  • http://api.jquery.com/jQuery.when/
like image 189
Thinking Sites Avatar answered Sep 17 '22 18:09

Thinking Sites