Registering for jQuery(window).load(...) event, after the event has fired?
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 becau开发者_开发技巧se 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!
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.
This problem bit me too. I guess it can be risky to add 'load' callback to late after the page loads — since it won't get called at all if the 'load' event has already been fired!
I completely agree — I too expected my callback to get called immediately since the event it was supposed to wait on was already complete. It seems like that would be more consistent with the way the document 'ready' event immediately fires its callbacks if the document is already ready...
Here is my workaround, written in CoffeeScript:
$(window).on 'load', ->
window._loaded = true
window.on_window_load_safe = (callback) ->
if window._loaded
# Since the load even already happened, if we tried to add a new callback now, it would not even
# get called. So just call the callback immediately now.
callback.call()
else
$(window).on 'load', ->
callback.call()
You can test it with something like this:
setTimeout(->
on_window_load_safe ->
console.debug 'on_window_load_safe called me'
, 2000)
精彩评论