Categories: Snippets

Clear the browser cache of CSS or JavaScript Using PHP

Other than caching every hour, or every week, you may cache according to file data.

<script src="js/my_script.js?v=<?=md5_file('js/my_script.js')?>"></script>

or use file modification time:

<script src="js/my_script.js?v=<?=filemtime('js/my_script.js')?>"></script>

or use file modification every hour:

<script type="text/javascript" src="js/myscript.js?v=<?php echo date('YmdHis'); ?>"></script>

or Using Javascript

function reloadScripts(toRefreshList/* list of js to be refresh */, key /* change this key every time you want force a refresh */) {
    var scripts = document.getElementsByTagName('script');
    for(var i = 0; i < scripts.length; i++) {
        var aScript = scripts[i];
        for(var j = 0; j < toRefreshList.length; j++) {
            var toRefresh = toRefreshList[j];
            if(aScript.src && (aScript.src.indexOf(toRefresh) > -1)) {
                new_src = aScript.src.replace(toRefresh, toRefresh + '?k=' + key);
                // console.log('Force refresh on cached script files. From: ' + aScript.src + ' to ' + new_src)
                aScript.src = new_src;
            }
        }
    }
}

 

Share

Recent Posts

Current Site URL – Codeigniter

To get host url of current server simply replace application\config\config.php [crayon-68bd7d67dfbf2607030423/] with [crayon-68bd7d67dfbff003963855/]  

7 years ago

PHP: fopen error handling

You should first test the existence of a file by file_exists(). [crayon-68bd7d67e02ff419905901/] or simple solution…

7 years ago

Random String PHP

[crayon-68bd7d67e081d868169296/] Output the random string with the call below: [crayon-68bd7d67e0827092105220/]  

7 years ago

PHP function to make slug (URL string)

Note: from WordPress Use it like this: [crayon-68bd7d67e11f7864690350/] Code: [crayon-68bd7d67e1205903562122/]  

7 years ago

Include all files with in the folder

[crayon-68bd7d67e1ad6660501149/]  

7 years ago

How can I remove 3 characters at the end of a string in php?

[crayon-68bd7d67e1eb4582319642/] or [crayon-68bd7d67e1ebc911073575/]  

7 years ago