Is there a cross-browser onload event when clicking the back button?

后端 未结 15 2262
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 22:46

For all major browsers (except IE), the JavaScript onload event doesn’t fire when the page loads as a result of a back button operation — it only fires when the

相关标签:
15条回答
  • 2020-11-21 23:30

    I have used an html template. In this template's custom.js file, there was a function like this:

        jQuery(document).ready(function($) {
    
           $(window).on('load', function() {
              //...
           });
    
        });
    

    But this function was not working when I go to back after go to other page.

    So, I tried this and it has worked:

        jQuery(document).ready(function($) {
           //...
        });
    
       //Window Load Start
       window.addEventListener('load', function() {
           jQuery(document).ready(function($) {
              //...
           });
       });
    

    Now, I have 2 "ready" function but it doesn't give any error and the page is working very well.

    Nevertheless, I have to declare that it has tested on Windows 10 - Opera v53 and Edge v42 but no other browsers. Keep in mind this...

    Note: jquery version was 3.3.1 and migrate version was 3.0.0

    0 讨论(0)
  • 2020-11-21 23:32

    jQuery's ready event was created for just this sort of issue. You may want to dig into the implementation to see what is going on under the covers.

    0 讨论(0)
  • 2020-11-21 23:34

    I thought this would be for "onunload", not page load, since aren't we talking about firing an event when hitting "Back"? $document.ready() is for events desired on page load, no matter how you get to that page (i.e. redirect, opening the browser to the URL directly, etc.), not when clicking "Back", unless you're talking about what to fire on the previous page when it loads again. And I'm not sure the page isn't getting cached as I've found that Javascripts still are, even when $document.ready() is included in them. We've had to hit Ctrl+F5 when editing our scripts that have this event whenever we revise them and we want test the results in our pages.

    $(window).unload(function(){ alert('do unload stuff here'); }); 
    

    is what you'd want for an onunload event when hitting "Back" and unloading the current page, and would also fire when a user closes the browser window. This sounded more like what was desired, even if I'm outnumbered with the $document.ready() responses. Basically the difference is between an event firing on the current page while it's closing or on the one that loads when clicking "Back" as it's loading. Tested in IE 7 fine, can't speak for the other browsers as they aren't allowed where we are. But this might be another option.

    0 讨论(0)
提交回复
热议问题