How can I create a “first-load” event in html or Javascript?

前端 未结 5 528
暗喜
暗喜 2021-01-15 15:39

I\'m starter. I have an idea. I want to implement an event like this. Is it possible?



First visit event
         


        
5条回答
  •  [愿得一人]
    2021-01-15 15:51

    Localstorage is probably the way to go. Here is a bit of info on it: http://diveintohtml5.info/storage.html

    Basically it allows you to store small amounts of data on the user's machine (up to 5mb in most browsers). So all you need to do is set a flag in there letting you know that the user has already visited, and if that flag isn't present on page load, show the message.

    // Run function on load, could also run on dom ready
    window.onload = function() {
        // Check if localStorage is available (IE8+) and make sure that the visited flag is not already set.
        if(typeof window.localStorage !== "undefined" && !localStorage.getItem('visited')) {
             // Set visited flag in local storage
             localStorage.setItem('visited', true);
             // Alert the user
             alert("Hello my friend. This is your first visit.");   
        }
    }
    

    This should work in all browsers where local storage is available. See caniuse.com for reference. http://caniuse.com/#search=localstorage

提交回复
热议问题