Detect first page load with jQuery?

我的未来我决定 提交于 2019-12-04 19:27:12

问题


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 server side code page.ispostbasck. I have tested $(document).ready and it fires every time the page loads so this will not provide what I need. I have also tried the jQuery Load function - it also fires every page load. So by page load an example is that I have an HTML input tag on the page of type button and it does not fire a postback (like an asp.net button) but it does reload the page and fires $(document).ready

Thanks


回答1:


You will have to use cookie to store first load information:

if (! $.cookie("cookieName")){
   // do your stuff

   // set cookie now
   $.cookie("cookieName", "firstSet", {"expires" : 7})
}

Note: Above example uses jQuery Cookie plugin.




回答2:


An event doesn't exist that fires only when the page is loaded for the first time.

You should use jQuery's .ready() event, and then persist the fact that you've handled a first time page load using your method of choice (i.e. cookie, session variable, local storage, etc.).

Note: This method will never be fool proof unless you can store this information at the user level in a DB. Otherwise, as soon as the user clears their cookies, or whatever method you choose, the "first time loaded" code will fire again.




回答3:


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.




回答4:


The easy solution is to use jQuery ‘Once’ plugin

$(element).once('class-name', function() {
  // your javascript code
});


来源:https://stackoverflow.com/questions/9485099/detect-first-page-load-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!