Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect first page load with jQuery?

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

like image 915
Jim Evans Avatar asked Feb 28 '12 15:02

Jim Evans


1 Answers

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.

like image 179
Camille Sévigny Avatar answered Oct 29 '22 20:10

Camille Sévigny