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

查看:25
本文介绍了如何让浏览器看到 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 Display SVN Revision Number

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) . '">'."
";
}

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

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

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