开发者

How to run script only when user land on page

I have some script, written in Javascript, that show progress of loading site elements. I put this script on index.html file, so it runs only on main page. I开发者_开发技巧t works perfectly fine, but now it show progress when you land on index.html and also when you come back to main page from subpage which is my problem because main page is already cached and it's waste of time.

My question is: How to run script only when user land on page, not when he come back from subpage?


Try cookies to control when/when not to execute Javascript.


Create a cookie when the user hits index.html for the first time. Check for the cookie and only run the script if the cookie hasn't been set.

if(!isset($_COOKIE['something'])) {
    // run your loading script;
    setcookie('something','someValue');
}

Just be sure you have the above code before sending any output to the browser.


In addition to cookies you can use document.referrer:

<script>
if(document.referrer &&
document.referrer.indexOf("yoursite.com") == -1)
{
    // Page loading process script goes here.
}
</script>


<html>
<head>
..
</head>
<body onload="doStuff()">
...
<script type="text/javascript" language="JavaScript">
//<![CDATA[
 function doStuff(){
   //check condition
   if (readCookie('checkFirstTime')!=null) return;

   //otherwise set the flag && do your thing
   createCookie('checkFirstTime','yep',1);
   alert("Welcome home Yo!");
   ...
 }

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

//]]>
</script>
...
</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜