Home > Web Front-end > JS Tutorial > Does the `onload` Event Fire When the Back Button is Clicked?

Does the `onload` Event Fire When the Back Button is Clicked?

DDD
Release: 2024-12-10 01:09:13
Original
155 people have browsed it

Does the `onload` Event Fire When the Back Button is Clicked?

Does the Onload Event Fire on Browser Back Button Click?

When targeting major browsers such as Firefox, Opera, Safari, and IE, the onload event in JavaScript fails to trigger when a page is loaded via the back button. It only fires during the initial page load.

Achieving Cross-Browser Compatibility

To overcome this restriction and handle back button events in all major browsers, a creative solution has been discovered using jQuery. By adding an empty onunload event listener to the body, Safari, Opera, and Mozilla inadvertently trigger a page reload. This action mimics the desired onload functionality.

Here's a simple code example:

<body onunload="">
  <script type="text/javascript">
    alert('first load / reload');
    window.onload = function(){alert('onload')};
  </script>
  <a href="http://stackoverflow.com">click me, then press the back button</a>
</body>
Copy after login

Upon clicking the link and pressing the back button, you'll observe that the JavaScript alerts are triggered, indicating the page reload.

Consideration

Keep in mind that this workaround can potentially slow down your page for users. It's recommended to carefully evaluate whether this approach truly aligns with your application's needs.

The above is the detailed content of Does the `onload` Event Fire When the Back Button is Clicked?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template