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

deferred-loading, javascript, jquery

Solution

Defer should cause the script to be added to a queue that is processed after the page is completely loaded. According to the spec deferred scripts should be added to the queue in the order they came onto the page.

However different browsers have done slightly different things with the order. IE seems to run defer scripts in the order they finished loading rather than the order they occurred on the page. So you seeing the error sporadically because sometimes it's loading them in the right order and sometimes not.

See this post on hacks.mozilla.com for a more exhaustive explanation and examples of how different browsers handle the ordering of the defer queue.

Problem

I am trying to figure out a problem with some code 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 = { } ``` Because of the defer attribute on the elements, is it safe to assume that when the `.ready()` calls `FOO.init()` that `BAR` may still be undefined at that point b/c the code in `file2.js` hasn't executed yet because of the deferred execution? This would match a bug I am trying to track down (only occurs sporadically in IE), but I really want to understand why this is happening before I work on a solution. I have no idea why the original developer used `defer`, other than a cryptic commend about "he had to" do it this way.

Original source