如何让浏览器看到CSS和Javascript的变化? [英] How can I make the browser see CSS and Javascript changes?

查看:161
本文介绍了如何让浏览器看到CSS和Javascript的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CSS和Javascript文件不会经常更改,因此我希望它们由Web浏览器缓存。但我还希望Web浏览器查看对这些文件所做的更改,而不需要用户清除其浏览器缓存。还需要一个与版本控制系统(如Subversion)兼容的解决方案。

CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.


解决方案我看到涉及以查询字符串的形式向文件末尾添加一个版本号。

Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.

可以使用SVN修订版本号为您自动化: ASP.NET显示SVN版本号

Could use the SVN revision number to automate this for you: ASP.NET Display SVN Revision Number

您可以指定如何添加修订变量的另一个文件?也就是在HTML文件中,我可以在CSS或Javascript文件的URL中包含版本号。

Can you specify how you include the Revision variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file.

Subversion book 它说关于修订:此关键字描述此文件在存储库中更改的最后一个已知修订版本。

In the Subversion book it says about Revision: "This keyword describes the last known revision in which this file changed in the repository".


Firefox还允许按 CTRL + R 重新载入特定页面上的所有内容。

Firefox also allows pressing CTRL+R to reload everything on a particular page.

为了说明我在寻找不需要用户做任何事情的解决方案。

To clarify I am looking for solutions that don't require the user to do anything on their part.

推荐答案

我发现如果将文件的最后修改的时间戳附加到URL的末尾,浏览器将在修改时请求文件。例如在PHP中:

I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP:

function urlmtime($url) {
   $parsed_url = parse_url($url);
   $path = $parsed_url['path'];

   if ($path[0] == "/") {
       $filename = $_SERVER['DOCUMENT_ROOT'] . "/" . $path;
   } else {
       $filename = $path;
   }

   if (!file_exists($filename)) {
       // If not a file then use the current time
       $lastModified = date('YmdHis');
   } else {
       $lastModified = date('YmdHis', filemtime($filename));
   }

   if (strpos($url, '?') === false) {
       $url .= '?ts=' . $lastModified;
   } else {
       $url .= '&ts=' . $lastModified;
   }

   return $url;
}

function include_css($css_url, $media='all') {
   // According to Yahoo, using link allows for progressive 
   // rendering in IE where as @import url($css_url) does not
   echo '<link rel="stylesheet" type="text/css" media="' .
        $media . '" href="' . urlmtime($css_url) . '">'."\n";
}

function include_javascript($javascript_url) {
   echo '<script type="text/javascript" src="' . urlmtime($javascript_url) .
        '"></script>'."\n";
}

这篇关于如何让浏览器看到CSS和Javascript的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆