Force the browser to load updated css or javascript files

As a website developer, you have probably experienced that changes in CSS or Javascript files are not updated. You may resort to hard-refresh (shift + f5 or shift + R). There is a better way to force the browser to load only updated css or javascript files.

Javascript and CSS files are often cached by browsers so that they are not loaded every time you move from one page to another. If you are working with a website, you must therefore reload the page with the shift key held down. By doing this, you tell the browser to reload the files.

But you do that because you know you’ve made a change in the css or javascript file. Someone who visits your page will not know that you have made changes.

To avoid this, it is a good idea to add an attribute to the link of the file you are going to import.

By an attribute I mean the following:

https://www.example.com/javascriptfil.js?attribut=1234

What happens after the question mark on the line above are attributes. In this case I have added an attribute that I have given the name attribute and the value 1234.

When you add a css or javascript file to wordpress you use the command wp_enqueue_style or wp_enqueue_script depending on what you should import or include.

You include a style as follows:

// wp_enqueue_style('handle', 'source', 'deps, 'version', 'media');

// Eksempel:
wp_enqueue_style('nettsidenavn_desktop_stil', 
get_template_directory_url()."/assets/css/nettsidenavn-desktop.css",
null,
'2.2',
'');

In the example above, I have set the value to 2.2. This will cause that when wordpress loads the page it will say ?ver=2.2 after the address of the css file.

If you want to do this manually further, just change to, for example, 2.3 when you have made a change in the css file.

However, it is easy to forget to change the version number.

Therefore I do the following instead:

// wp_enqueue_style('handle', 'source', 'deps, 'version', 'media');

// Eksempel:
wp_enqueue_style('nettsidenavn_desktop_stil', 
get_template_directory_url()."/assets/css/nettsidenavn-desktop.css",
null,
filemtime(get_template_directory_url()."/assets/css/nettsidenavn-desktop.css"),
'');

filemtime is a PHP function which returns the time of when the file was last modified in a timestamp format. So not as an actual date – although that is also possible – but as a long number.
This number can be, for example, 90748932.

The advantage of this solution is that the number does not change if you do not make changes to the file. This way, the file will not be reloaded every time the visitors to your page click around and reload the page.

The fewer files or data the browser needs to fetch each time, the faster the page loads.