Detect first page load with jQuery?

后端 未结 4 1667
耶瑟儿~
耶瑟儿~ 2021-02-14 08:15

I need to detect the first time a page loads in jQuery so that I can perform some actions only when the page loads the first time a user navigates to that page. Similar to serve

4条回答
  •  日久生厌
    2021-02-14 08:53

    I just ran into this problem and this is how I handled it. Keep track of the first time the page loads by using a variable initialLoad:

    var initialLoad = true;
    
    $(document).ready(function() {
        ...
        ...
        ... 
    
        initialLoad = false;
    
    });
    

    Then in other functions, you can do this:

    if (initialLoad) {
        //Do work that is done when the page was first refreshed/loaded.
    } else {
        //Do work when it's not the initial load.
    }
    

    This works well for me. If the user is already on the page and some jQuery functions run, I now know if that user just loaded the page or if they were already on the page.

提交回复
热议问题