Wednesday, May 2, 2012

Nested Async Javascript

I am using the technique specified http://friendlybit.com/js/lazy-loading-asyncronous-javascript/ to load external javascript when the window.onload() is triggered. But if the script itself contains some registration of load event handler then they might not get called as the event has been (somehow) passed. In order to confirm, I added the following code to the external javascript file that is loaded as mentioned above:





(function() {
if (window.attachEvent)
window.attachEvent('onload', alert("ok"));
else
window.addEventListener('load', alert("ok"), false);
})();



This alert actually appears which make me think, whether the onload is called twice or does loading javascript means loading the script, running its "global" part and then moving on to the next listener. In the latter case, if another listener is added to onload event while running its "global" part then this behavior is correct. But I am not sure of this and would appreciate if someone more experienced could clarify/confirm it.





No comments:

Post a Comment