Bachalo
Bachalo

Reputation: 7219

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

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?

Upvotes: 7

Views: 17928

Answers (2)

Nathan
Nathan

Reputation: 11159

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.

Upvotes: 1

iambriansreed
iambriansreed

Reputation: 22251

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?

Upvotes: 2

Related Questions