Home  >  Article  >  Web Front-end  >  How to automatically clean up the cache of js and css files

How to automatically clean up the cache of js and css files

小云云
小云云Original
2017-11-30 10:02:262665browse

As a developer, we often need to clear the cache. We often reference css and js files. Caching problems often occur after updating the files, but sometimes we have clearly changed the code and when accessing it on the browser But there is no change, so let’s share with you several solutions.

1. Manually clear the browser cache

2. Add the version number (such as layout.css?v=1)

I personally think method 2 is faster because clearing the browser The browser cache still needs to wait for the browser to respond. But it is troublesome to change the version number every time, so you need to find a way to automatically add the version number.

The following are the methods I collected:

Method 1: You can automatically add the version number to html through js

<script type="text/javascript">  
document.write("<link rel=&#39;stylesheet&#39; type=&#39;text/css&#39; href=&#39;/css/layout.css?v="+new Date().getTime()+"&#39;>");   
</script>

Method 2: If it is a jsp page, you can use java code to generate a timestamp (if it is a jsp page, you can also use method 1, but this method is more convenient)

<link rel="stylesheet" type="text/css" href="/css/layout.css?v=<%=System.currentTimeMillis() %>">

Method 3: Use other methods to add the version number, such as automatic configuration with node.js, etc.

ps: The purpose of clearing the cache is to see the update of the page in time. When we When putting the page online (that is, deploying it to the official environment without making any changes), it is recommended to fix the version number, because cached pages are accessed faster, and you can change the fixed version number when it needs to be updated.

The above content is how to automatically clean up the cache of js and css files in HTML pages. You can try this method when you encounter such problems. I hope it can help you.

Related recommendations:

Yii clear cache method_php example

##php regularly deletes files under the folder (clear cache files)

How to use php code to delete folders and clear cache instances?

The above is the detailed content of How to automatically clean up the cache of js and css files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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