Register for jQuery (window) .load (...) event after event has been fired?

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

I have an external JS file that is dynamically inserted into the page after the window load event. Inside this JS file, I have an instruction as follows:

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

The question I have will lead to the execution of the alert () operator above, because by the time my function above is registered in the window load event, the event is already running. I would expect that the warning, which will be issued immediately after the moment the event is waiting, has already been completed.

I appreciate any ideas.

Thanks!

+4
source share
2 answers

No, this does not work, however you can trigger the event after insertion as follows:

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

This will run this code.

Using document.ready will be immediately generated after the document is turned on after the document is ready, but $(window).load(function() {... }) explicitly bound to the window load event that was already running.

+3
source

This problem also bit me. I think it might be dangerous to add the "load" callback to the end after the page loads, since it will not be called at all if the "load" event has already been fired!

I completely agree - I also expected that my callback would be called immediately after the event that it should have been waiting for was already completed. It looks like this will be more consistent with how the event โ€œreadyโ€ for the document immediately launches 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 check it something like this:

  setTimeout(-> on_window_load_safe -> console.debug 'on_window_load_safe called me' , 2000) 
+1
source

Source: https://habr.com/ru/post/1305155/


All Articles