Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  74] [ 2]  / answers: 1 / hits: 71793  / 9 Years ago, thu, august 6, 2015, 12:00:00

I am wondering if there is a way to execute a JavaScript function once only on the first ever page load and then not execute on any subsequent reloads.



Is there a way I can go about doing this?


More From » javascript

 Answers
6

The code below will execute once the onload event fires. The statement checks if the onetime function has NOT been executed before by making use of a flag (hasCodeRunBefore), which is then stored in localStorage.



window.onload = function () {
if (localStorage.getItem(hasCodeRunBefore) === null) {
/** Your code here. **/
localStorage.setItem(hasCodeRunBefore, true);
}
}


Note: If the user clears their browsers' localStorage by any means, then the function will run again because the flag (hasCodeRunBefore) will have been removed.



Good news...



Using localStorage can be tedious because of operators and long winded function names. I created a basic module to simplify this, so the above code would be replaced with:



window.onload = function () {
if (!ls.exists('has_code_run_before')) {
/** Your code here... **/
ls.set.single('has_code_run_before', true);

/** or... you can use a callback. **/
ls.set.single('has_code_run_before', true, function () {
/** Your code here... **/
});
}
};


Update #1



Per @PatrickRoberts comment, you can use the in operator to see if a variable key exists in localStorage, so



if (localStorage.getItem('hasCodeRunBefore') === null)


becomes



if (!('hasCodeRunBefore' in localStorage))


and is less verbose and a lot cleaner.



Secondly, you can set values as you would an object (localStorage.hasCodeRunBefore = true) though it will be stored as a string, not as boolean (or whatever data type your value is).


[#65505] Wednesday, August 5, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dahlias

Total Points: 730
Total Questions: 104
Total Answers: 101

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;