0

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.

1 Answer 1

1

I believe that alert is being called when the event is attached, not when the window is loaded. That's because you're executing the alert function, and then passing the result of alert (which will be null) as the second parameter to attachEvent.

What you are executing is essentially:

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

To test what you describe in your question, you need to modify your code:

(function() {
   if (window.attachEvent)
       window.attachEvent('onload', function() {alert("ok");});
   else
       window.addEventListener('load', function() {alert("ok");}, false);
})(); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.