简体   繁体   中英

How can I execute a JavaScript function on the first page load?

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?

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).

All JavaScript must execute every time a page loads. If the script is on the page, it will execute.

The logic that is executed within the JavaScript included on the page may execute in a different manner depending on the page state, input provided, and any other signals it receives, be it from the server or the client.

If you're using a server side language, you might choose to render a script conditionally, such as the first time a user logs in.

If you need to include the javascript irrespective of context, then you need to listen to other signals.

The simple modern solution is to make use of localStorage . localStorage can be used to store custom string values on custom key values for any given domain.

The code to make use of this would look like:

if (localStorage['...my key here...'] === '...my expected value here...') {
    // The page has been visited before
} else {
    // The page has not been visited before
    // OR
    // The user or script has cleared the localStorage value
}
localStorage['...my key here...'] = '...my expected value here...';

That's all well and good if you just need things to work on the client alone. Sometimes you might need the server to know whether or not the page has been visited before.

The (less)simple solution is to use document.cookie :

if (/(?:^|;\s*)...my key here...=...my expected value here...(?:;|$)/.test(document.cookie)) {
    // the page has been visited before
} else {
    // The page has not been visited before
    // OR
    // The user or script has cleared the cookie
}
document.cookie = '...my key here...=...my expected value here...';

If you need to defer the execution until the page has finished loading, then simply include the script in an onload callback, either by assigning the event to the window:

window.onload = function () {
    // do stuff when the page has loaded
    //this will override any other scripts that may have been assigned to .onload
};

or by binding the event handler to the window:

window.addEventListener('load', function () {
    // do stuff when the page has loaded
}, false);

 function toBeExecutedOnFirstLoad(){ // ... } if(localStorage.getItem('first') === null){ toBeExecutedOnFirstLoad(); localStorage.setItem('first','nope!'); } 

It depends on what first page load means to you. It's subjective.

If you want the function to fire once the DOM has been parsed, but only the HTML and no other external resources, bind it to the DOMContentLoaded event.

document.addEventListener('DOMContentLoaded', fn);

Otherwise, if you want to wait for external resources to be loaded and then fire the event, you should bind it to the window object's load event like so:

window.addEventListener('load', fn);

Here are some links from the Mozilla Developer Network that explain the what I just said in more detail:

https://developer.mozilla.org/en-US/docs/Web/Events/load

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

Good luck!

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