Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do so many Javascript scripts append random numbers to things? Collision?

Tags:

javascript

url

I've been learning JavaScript recently, and I've seen a number of examples (Facebook.com, the Readability bookmarklet) that use Math.rand() for appending to links.

What problem does this solve? An example parameter from the Readability bookmarklet:

_readability_script.src='http://lab.arc90.com/....script.js?x='+(Math.random());

Are there collisions or something in JavaScript that this is sorting out?

like image 413
Alex Mcp Avatar asked Nov 29 '22 19:11

Alex Mcp


2 Answers

As Rubens says, it's typically a trick employed to prevent caching. Browsers typically cache JavaScript and CSS very aggressively, which can save you bandwidth, but can also cause deployment problems when changing your scripts.

The idea is that browsers will consider the resource located at http://www.example.com/something.js?foo different from http://www.example.com/something.js?bar, and so won't use their local cache to retrieve the resource.

Probably a more common pattern is to append an incrementing value which can be altered whenever the resource needs to change. In this way, you benefit by having repeat requests served by the client-side cache, but when deploying a new version, you can force the browser to fetch the new version.

Personally, I like to append the last-modified time of the file as as a Unix timestamp, so I don't have to go hunting around and bumping version numbers whenever I change the file.

like image 74
Rob Avatar answered Dec 04 '22 22:12

Rob


Main point is to avoid browser caching those resources.

like image 31
Rubens Farias Avatar answered Dec 04 '22 23:12

Rubens Farias