Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the javascripts loaded synchronously if one uses document.write?

Is it the same if you load javascript to the page like this:

<script src="http://domain.net/script.js" type="text/javascript"></script>

and like this

<script type="text/javascript">
  document.write("<script src='http://domain.net/script.js' type='text/javascript'></script>");

I have a lot of the dependencies in js and want to configure then in as a separate array, which are just bundled in index.html in the way like:

<script type="text/javascript">
  for (i in config.files.javascripts) {
    document.write("<script src='config.files.javascripts[i]' type='text/javascript'></script>");
  }
</script>

The question is - should it work as expected so that the next file is not executed until the previous one is loaded?

This is there is no server side in the front-end I'm doing and it will also sometimes work as widget though for the dev and test we should load files unmerged and uncompressed to test.

Thanks!

like image 699
lyuba Avatar asked Mar 19 '11 21:03

lyuba


1 Answers

To answer your question: Yes, scripts loaded with document.write are guaranteed to execute in the order written.

Same applies to scripts loaded using the W3C DOM methods.

var scriptElm = document.createElement('script');
scriptElm.defer = true; // Causes faster (parallel) loading in some browsers.
scriptElm.src = 'path/to/script.js';
document.getElementsByTagName('head')[0].appendChild( scriptElm );

That said, document.write() is generally considered really bad practice (for a variety of reasons) and can lead to breakage and annoying edge-case problems later on. I, therefore, recommend that you use the W3C DOM injection shown above, if nothing else.

- - - -
Then there are script loading libraries that make this sort of resource loading easier, more elegant, and sometimes even faster. Some load scripts in parallel but execute in a predictable order - like the one already linked to by @CoBaLt2760 http://www.dustindiaz.com/scriptjs

jQuery also has a very simple method $.getScript( 'path/to/script.js' ); (documentation) that you can use. If memory serves me right, It uses simple W3C DOM injection.

Google "javascript loading" or some such, or search here on StackOverflow,com if you're interested in more links to such libraries.

like image 84
Már Örlygsson Avatar answered Oct 19 '22 01:10

Már Örlygsson