Reputation: 456
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?
Upvotes: 0
Views: 1733
Reputation: 152
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);
Upvotes: 1
Reputation: 235
Using removeEventListener is a good option:
var callback = function(){
...
}
window.removeEventListener('load',callback);
window.addEventListener('load',callback);
Upvotes: 0
Reputation: 1431
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
Upvotes: 0
Reputation: 1549
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);
}
Upvotes: 0
Reputation: 125
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
Upvotes: 0
Reputation: 370679
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
});
}
Upvotes: 1