0

How can I run js / jQuery when it is first time a user is visiting my site / app.

The ways I can think of are through cookies or local storage, but which is proper?

gomangomango
  • 641
  • 9
  • 28

2 Answers2

1

I would use Cookies as this is the easiest and most supported way, also if you target older browsers - the local storage might not be consistent.

Thus, for such a simple task - use cookies.

Roman
  • 4,194
  • 14
  • 52
  • 77
  • Can you show me a good and supported way to use cookies in js / jQuery ? – gomangomango Mar 15 '14 at 22:37
  • Check this one - http://stackoverflow.com/questions/1458724/how-to-set-unset-cookie-with-jquery – Roman Mar 15 '14 at 22:43
  • I don't think I am doing it right as the first-visit code isn't running. Also, it says the cookie is undefined even though I'm setting it to either true or false. Here's what I'm doing: `if($.cookie('firstVisit') === true) $.cookie('firstVisit', false); else $.cookie('firstVisit', true);` – gomangomango Mar 16 '14 at 01:00
  • Did you download the jQuery plugin and install it? Check in the browser console you don't get errors – Roman Mar 16 '14 at 07:56
  • Great :) If you've done anything different from the link, please share for future generations. – Roman Mar 20 '14 at 08:44
0

Cookies are the best solution because they are less expensive on the server. Also you don't need to save more data than just the cookie itself, meaning the user has already visited your website. Sessions usually are more complex and used to store more information than a cookie could (or should) hold..

For more information see Cookie VS Session

Community
  • 1
  • 1
enapupe
  • 10,639
  • 3
  • 24
  • 41