Home > Web Front-end > JS Tutorial > How to disable caching in javascript

How to disable caching in javascript

青灯夜游
Release: 2023-01-05 16:10:01
Original
5283 people have browsed it

Method: Add a question mark and a random number after the js file URL, for example "a.js?223". Principle: Adding a number after the URL of the resource will not affect file loading, but if the number changes, the browser will think it is a brand new file and will re-download the cache. Therefore, the function of adding a number is to force the browser to Call the new address to prevent caching.

How to disable caching in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript disables caching

Method: Adding question marks and numbers after css and js can prevent caching

When the browser issues an http request, it will load various resources, such as: HTML documents, videos, pictures, CSS and JS, etc. For these resources with unchanged URLs, the browser will save them in the local cache. The next time you visit the same website, you can load them directly to speed up access.

This caching strategy of the browser speeds up access on the one hand, but on the other hand it also encounters a problem, that is, it cannot load the latest css and js files in time.

In order to solve this problem, we will add question marks and some random characters after the css and js links.

Similar to index.js?20210489

Example:

<html>
<head>
<script type="text/javascript">
    document.write("<script src=&#39;**.js?"+Math.random()+"&#39;><\/script>");
</script>
 
</head>
</html>
Copy after login

Principle: Add a number after the url of the resource, for the file Loading will not have any impact, but if the number changes, the browser will think it is a brand new file, will re-download the cache, and will not read the previously cached file, so the function of adding a number is to force the browser Call the new address to prevent caching.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to disable caching in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template