'Run window.addEventListener('load' ...) only once
I am wondering if there is any way to run window.addEventListener('load' ...)
only the first time the specific page is loaded.
I tried just setting a flag called loaded
to false
, and only run the code inside the eventListener
if loaded === false
. Then once it's run, I set loaded to true
. But does not work, still runs every time.
Can I perhaprs remove the eventListener once its run?
Solution 1:[1]
- Easy way: you can use web storage that is if it's supported. Something like:
if (!localStorage.getItem("listenerLoaded")) {
window.addEventListener('load'...)
localStorage.setItem("listenerLoaded", true);
}
A bit tedious work would be using:
2. cookie(still browser needs support etc).
3. ajax and hold session
Solution 2:[2]
Keep a localStorage
item that contains an array corresponding to all pages that have been loaded so far. Only attach the listener if that page isn't stored in localStorage
yet. For example:
const { href } = window.location;
const alreadyLoaded = JSON.parse(localStorage.loaded || '[]');
if (!alreadyLoaded.includes(href)) {
alreadyLoaded.push(href);
localStorage.loaded = JSON.stringify(alreadyLoaded);
window.addEventListener('load', () => {
// rest of your code
});
}
Solution 3:[3]
No it is not possible a a new execution context will be created every time that page loads. You can try something like localStorage to save the state.
LocalStorage API helps you to save data which can be accessed later.it is an Object which can be used to access the current origin's local storage space.
For more info visit: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Solution 4:[4]
Simply set a value in local storage once listener gets loaded then read that value before adding it again.
if (!localStorage.getItem("isLoaded")) {
window.addEventListener('load' ...)
localStorage.setItem("isLoaded", true);
}
Solution 5:[5]
Using removeEventListener is a good option:
var callback = function(){
...
}
window.removeEventListener('load',callback);
window.addEventListener('load',callback);
Solution 6:[6]
Set the once property to true and it will run only once (doesn't work with Internet explorer)
More information here
const once = {
once : true
};
window.addEventListener('load',callback, once);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | CertainPerformance |
Solution 3 | Devinder |
Solution 4 | Muneeb |
Solution 5 | Carlos Eduardo Ki Lee |
Solution 6 | Davi Areias |