views:

723

answers:

1

Hello,

I am new to the group and just had a simple question about the jQuery(window).load(function() {});.

I have an external JS file that gets inserted dynamically on the page "after" the window load event occurs. Inside this JS file I have a statement as follows:

jQuery(window).load(function() {
    alert("Something");
});

The question I have is, would the alert() statement above get executed because by the time my above function gets registered to the window load event, the event has already fired. I would expect the alert above to fire immediately since the event it is supposed to wait on, is already complete.

I appreciate any ideas.

Thanks!

+1  A: 

No, it would not fire, however, you can invoke the event after inserting like this:

$(window).load(); //or.. $(window).trigger('load');

This will trigger that code to run.

Using document.ready will fire immediately when included after the document is already ready, but $(window).load(function() {... }) is explicitly binding to the window's load event, which has already fired.

Nick Craver
Thanks! I expected the behavior to be a little more intelligent but I get your point here. I will try to register my function to the load event before it actually fires. (More in the comment above).
stony_dreams