Appending query string to all .js and .css files to prevent caching?

16,958

Solution 1

I think this is fine, but as far as best practice is concerned that is really subjective.

The most popular, most widely used CMS uses this method so I consider it the way to go.

What people don't understand is this method isn't the simplest way to signal to browsers that this file can be cached but is recached only when the version changes.

Short answer to the first question, yes.

As far as the second question "production-development" is an oxymoron. Which is it production or development?

Solution 2

If you're doing something server-side, it's very easy to prevent caching for when your file changes:

PHP:

<script src="<?= $file.’?’.filemtime($file); ?>">

node.js

res.write('<script src="' + file + '?' + new Date(fs.statSync(file).mtime).getTime());

This appends the modified timestamp to the file, so it'll only prevent caching when the file has been modified.

Share:
16,958
Bachalo
Author by

Bachalo

Storyteller and constant beginner

Updated on June 09, 2022

Comments

  • Bachalo
    Bachalo almost 2 years

    Going thru a tutorial on building a web app and it has been recommended to ALWAYS append a query string "?v=1" to all .css and .js files to prevent caching.

    Is this a 'best practice'?

    Should the query string only be used during production-development?