Preload with Cookie or Session

0

Hello everyone, how are you? I'm using a preload code this is working fine, but the problem is that every time you access the site loads the preload this bothers a lot .. I would like it to load only once per access, example if you continue browsing it will not load, the access will show the preload again.

    
asked by anonymous 18.11.2016 / 23:59

1 answer

1

You can set a variable in $_SESSION and check if it was set at the time of displaying the preload, in the case of PHP it would look something like this:

<?php
session_start();

if (empty($_SESSION['preload'])) {
   $_SESSION['preload'] = true;
  //código para mostrar o preload
}
?>

With JS you can do using cookie for example:

function setCookie(cname, cvalue, days) {
    var d = new Date();
    var expires;
    if (days) {
        d.setTime(d.getTime() + (days*24*60*60*1000));
        expires = "expires="+ d.toUTCString();
    }else {        
        expires = "";
    }
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
        }
    }
    return "";
}

function checkPreload() {
    var preload = getCookie("preload");
    if (preload == "") {
        console.log("mostrar preload");
        setCookie("preload", 1, 1);
    } else {
        console.log("já mostrou o preload");
    }
}

checkPreload();
    
19.11.2016 / 00:43