Interaction between jQuery.ready () and <script defer>

I am trying to figure out a problem with some code that I have inherited.

I have an HTML page with

<script type="text/javascript" src="file1.js" defer="defer"></script> <script type="text/javascript" src="file2.js" defer="defer"></script> </body> </html> 

file1.js has

 FOO = { init : function () { var bar = BAR; } } $(document).ready(FOO.init); 

file2.js has

 var BAR = { } 

Due to the defer attribute for elements, we can safely assume that when .ready() calls FOO.init() that the BAR can still be undefined at this point b / c, the code in file2.js deferred execution?

This will correspond to the error that I am trying to track (only happens occasionally in IE), but I really want to understand why this happens before I work on the solution. I have no idea why the original developer used defer , with the exception of criticisms that "he should have" done it that way.

+8
javascript jquery deferred-loading
source share
2 answers

The delay should lead to the addition of the script to the queue, which is processed after the page is fully loaded. According to the specification, pending scripts should be added to the queue in the order in which they hit the page.

However, different browsers did slightly different things with order. IE seems to run deferral scripts in the order in which they finished loading, and not in the order they appear on the page. Thus, you observe the error sporadically, because sometimes it loads them in the correct order, and sometimes not.

See this post on hacks.mozilla.com for a more comprehensive explanation and examples of how different browsers handle the deferral queue order.

+2
source share

Deffering in javascript prefers the browser when to interpret the script, in some optimal conditions, such as chrome, the script loads when the page loads, then it is analyzed and interpreted. If you use deferral as described above, you can never be sure that the script is loaded first or when the interpretation is complete.

BAR can be undefined on one load page and be defined in reload (in cache) or the second script was loaded first.

To verify this, try making changes to one of the scripts to force a new load and interpretation and see what race conditions exist.

0
source share

All Articles