简体   繁体   中英

How can I use the JavaScript bodyOnLoad() function to be executed only once?

How can I use the JavaScript bodyOnLoad() function to be executed only once?

I just need it to be loaded only once and not each time that the page refreshes. Is there another function that can provide this functionality?

Thanks!

You can do it easily using hash:

(function() {
  if(location.hash) return;
  document.addEventListener("DOMContentLoaded",bodyOnLoad);
  location.hash = "loaded";
})();

function bodyOnLoad() {
  alert("alerting only on the first load");
}

It alerts only for the first time, if you try to reload by F5.

It is easy to implement, but if you use hash for something else or if you don't want to alter url, Kamil and Rajesh in the comments at your question have better ideas.

Note that DOMContentLoaded doesn't work in IE<9. For loder browser support, read about cross-browser fallback . Also note that altering location.hash doesn't reload the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM