Why do so many JavaScript scripts append random numbers to things? collision?
P粉729518806
P粉729518806 2023-11-04 20:00:04
0
2
733

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粉729518806
P粉729518806

reply all (2)
P粉378264633

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

    P粉144705065

    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 athttp://www.example.com/something.js?foois different fromhttp://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.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!