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

后端 未结 15 2261
被撕碎了的回忆
被撕碎了的回忆 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:25

    I couldn't get the above examples to work. I simply wanted to trigger a refresh of certain modified div areas when coming back to the page via the back button. The trick I used was to set a hidden input field (called a "dirty bit") to 1 as soon as the div areas changed from the original. The hidden input field actually retains its value when I click back, so onload I can check for this bit. If it's set, I refresh the page (or just refresh the divs). On the original load, however, the bit is not set, so I don't waste time loading the page twice.

    <input type='hidden' id='dirty'>
    
    <script>
    $(document).ready(function() {
      if ($('#dirty').val()) {
        // ... reload the page or specific divs only
      }
      // when something modifies a div that needs to be refreshed, set dirty=1
      $('#dirty').val('1');
    });
    </script>
    

    And it would trigger properly whenever I clicked the back button.

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

    If I remember rightly, then adding an unload() event means that page cannot be cached (in forward/backward cache) - because it's state changes/may change when user navigates away. So - it is not safe to restore the last-second state of the page when returning to it by navigating through history object.

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

    I ran into a problem that my js was not executing when the user had clicked back or forward. I first set out to stop the browser from caching, but this didn't seem to be the problem. My javascript was set to execute after all of the libraries etc. were loaded. I checked these with the readyStateChange event.

    After some testing I found out that the readyState of an element in a page where back has been clicked is not 'loaded' but 'complete'. Adding || element.readyState == 'complete' to my conditional statement solved my problems.

    Just thought I'd share my findings, hopefully they will help someone else.

    Edit for completeness

    My code looked as follows:

    script.onreadystatechange(function(){ 
       if(script.readyState == 'loaded' || script.readyState == 'complete') {
          // call code to execute here.
       } 
    });
    

    In the code sample above the script variable was a newly created script element which had been added to the DOM.

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

    Unload event is not working fine on IE 9. I tried it with load event (onload()), it is working fine on IE 9 and FF5.

    Example:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        jQuery(window).bind("load", function() {
            $("[name=customerName]").val('');
        });
    </script>
    </head>
    <body>
        <h1>body.jsp</h1>
        <form action="success.jsp">
            <div id="myDiv">
    
            Your Full Name: <input name="yourName" id="fullName"
                value="Your Full Name" /><br> <br> <input type="submit"><br>
    
            </div>
    
        </form>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-21 23:28

    Some modern browsers (Firefox, Safari, and Opera, but not Chrome) support the special "back/forward" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). This allows it to re-load the page quicker and exactly as the user left it.

    The load event is not supposed to fire when the page is loaded from this bfcache. For example, if you created your UI in the "load" handler, and the "load" event was fired once on the initial load, and the second time when the page was re-loaded from the bfcache, the page would end up with duplicate UI elements.

    This is also why adding the "unload" handler stops the page from being stored in the bfcache (thus making it slower to navigate back to) -- the unload handler could perform clean-up tasks, which could leave the page in unworkable state.

    For pages that need to know when they're being navigated away/back to, Firefox 1.5+ and the version of Safari with the fix for bug 28758 support special events called "pageshow" and "pagehide".

    References:

    • Webkit: http://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
    • Firefox: https://developer.mozilla.org/En/Using_Firefox_1.5_caching.
    • Chrome: https://code.google.com/p/chromium/issues/detail?id=2879
    0 讨论(0)
  • 2020-11-21 23:29

    OK, I tried this and it works in Firefox 3, Safari 3.1.1, and IE7 but not in Opera 9.52.
    If you use the example shown below (based on palehorse's example), you get an alert box pop-up when the page first loads. But if you then go to another URL, and then hit the Back button to go back to this page, you don't get an alert box pop-up in Opera (but you do in the other browsers).

    Anyway, I think this is close enough for now. Thanks everyone!

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    <meta http-equiv="expires" content="0">
    <script src="jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready( 
                        function(){
                          alert('test');
                        }
                     );
    </script>
    </head>
    <body>
    <h1>Test of the page load event and the Back button using jQuery</h1>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题