Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

Deffering in javascript gives preference to the browser of when to interpret the script, in some optimal conditions like with chrome the script is downloaded while the page is being loaded then parsed and interpreted. If you use defer like the above you can never be certain which script is loaded first or when the interpretation is complete.

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

To test this try make a change to one of the scripts to force a new download and interpretation and see what race conditions exist.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top