Automatically clear browser cached files when you upload a new version

 
 
 

If you are regularly making changes to your CSS or JavaScript you will probably have run into caching issues with browsers, maybe changes you have made and uploaded are not showing up on the live server or perhaps you can see changes but your clients or colleagues can't see them. This usually comes down to the browser caching the files locally and not refreshing the changes when you've uploaded a new file.

Thankfully theres a cool way to force the browser to refresh the file when you have made a change, we can do this by appending some query string to the end of the file name, this query string doesn't need to actually do anything its just a neat little trick to make the browser think it is a different file and load the new version.

Having to remember to update the query string after every change is quite irritating and not very good for your workflow so I made this neat little helper function that grabs the files latest file modification time and returns the file location along with an appended query string:


if(!function_exists('file_refresh')) {

    function file_refresh($file_location = '') {

        if($file_location) {
            if($file_updated_time = @filemtime($_SERVER["DOCUMENT_ROOT"] . $file_location)) {
            return $file_location . '?v=' . $file_updated_time;
        }

    }
    return FALSE;
    }
}

If you are running a PHP framework like CodeIgniter or Laravel then you just need to add the function to a helper file, remember to load the helper file before trying to use it. When you do need to use the function just call it and pass through the location whenever you are linking to your CSS or JS, make sure that you echo the returned string so the browser can load the file:




When the file hasn't changed the same modified time is returned which will tell the browser to load a cached version.