search

Home  >  Q&A  >  body text

Why do so many JavaScript scripts append random numbers to things? collision?

I've been learning JavaScript lately, and I've seen many examples of using Math.rand() to append to links (Face book.com, readability bookmarks).

What problem does this solve? Example parameters in the Readability bookmarklet:

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

Are there conflicts or issues in JavaScript that need to be resolved?

P粉729518806P粉729518806419 days ago898

reply all(2)I'll reply

  • P粉378264633

    P粉3782646332023-11-05 15:56:01

    The key point is to prevent the browser from caching these resources.

    reply
    0
  • P粉144705065

    P粉1447050652023-11-05 11:47:29

    As Rubens said, this is often a trick used to prevent caching. Browsers tend to cache JavaScript and CSS very aggressively, which can save you bandwidth, but can also cause deployment issues when changing scripts.

    The idea is that the browser will think that a resource located at http://www.example.com/something.js?foo is different from http://www.example.com/something .js?bar, so the local cache is not used to retrieve the resource.

    Probably a more common pattern is to append an incrementing value that changes whenever the resource needs to change. This way you benefit from client-side caching to handle repeated requests, but when a new version is deployed you force the browser to fetch the new version.

    Personally, I like to append the file's last modified time as a Unix timestamp so that I don't have to hunt around and modify the version number every time I change the file.

    reply
    0
  • Cancelreply