Wednesday, May 19, 2010

Dynamic Script Loading

An update to "Include JS File from JS"

// then bind the event to the callback function
// there are several events for cross browser compatibility
script.onreadystatechange = callback;
script.onload = callback

In IE6, there is a possibility of the callback function being called twice. This is because script.onreadystatechange could be called in the several states:
0 uninitialized
1loading
2loaded
3interactive
4complete

You can include a handler to only callback when script is complete.
script.onreadystatechange= function () { if (this.readyState == 'complete') callback();}
The problem with this is that in IE7, you either get a 'loaded' event or 'completed' event. 
I would suggest using the JQuery method $.getScript("file.js", function() {}); or add the callback in the JS file that u are adding dynamically.
Reference: http://unixpapa.com/js/dyna.html

No comments:

Post a Comment