Let the browser not load cached CSS and JS methods

Source: Internet
Author: User

Most browsers now cache pictures, CSS, and JS files on the site to increase load speed. When your site changes CSS and JS, often because caching reasons can not immediately take effect.


Such old CSS and new Html may lead to errors, here is a small trick, you can ensure that the browser will not cache CSS and JS, only to the end of the file with a little bit of parameters, so the browser will think that this is a different file.

The code is as follows Copy Code

<link rel= "stylesheet" type= "Text/css" href= "/style.css?ver=123"/>

If you use PHP to take the current time as the version number, you will reload each time:

The code is as follows Copy Code

<link rel= "stylesheet" type= "Text/css" href= "/style.css?ver=<?php" echo Time ();?> "/>"

Of course, this will pay the price, completely break the browser's caching mechanism, resulting in the same time will reload the same CSS and JS

The best solution is to reload the CSS and JS files only when they are modified. To introduce a PHP filemtime () function, the Filemtime () function can return the last time the file was modified, so that the version changes only when the file is modified.

The code is as follows Copy Code

<?php $css = '/style.css '?>
<link rel= "stylesheet" type= text/css "href="? ver=<?php Echo $css. Filemtime ($CSS);?> "/>

Wordpress

If you use WordPress, you can mount the script via the scripting queuing mechanism provided by WordPress:

  code is as follows copy code

$css = get_ Stylesheet_directory (). '/css/style.css ';
Wp_enqueue_style (' style ', $css, NULL, Filemtime ($CSS));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.