How to execute function on first load using Javascript

Often there is a requirement to execute some function just once. For example : You need to show the promotional pop-up banner first time the customer visits the website.

There are many ways to achieve this. The way i use is by using cookie.

Before going into code, I’ll explain you what logic can be used.

When customer loads the website set some cookie value consider it as ‘Y’. Now check for the cookie value each time the page loads. If the cookie value is set. Don’t execute the method. If it isn’t set, execute the method and set the cookie value.

Below is the code for it.

window.onload= function(){
var fl = document.cookie.split(‘;’)
var cName = “firstLoad=”
for(var i=0; i<fl.length; i++){
var c = fl[i].trim();
if(c.indexOf(cName)==0){
var cookieVal = c.substring(cName.length,c.length);
}
}
if(cookieVal != “Y”){
document.cookie=”firstLoad=Y”
/* WRITE YOUR CODE OVER HERE */
}
else{
return “Already Loaded Once”
}
}

Here,

1) window.onload will execute the function evertime the window loads.
2) document.cookie.split(‘;’) will split the string of cookies into array.
3) substring(value1, value2) will get the part of the string.
4) document.cookie will set the cookie “firstLoad=Y”

Please write your comments below to provide your feedback and queries.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s