使用 javascript 重新加载 CSS 样式表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13721183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:44:18  来源:igfitidea点击:

Reload CSS stylesheets with javascript

javascriptjqueryhtmlcssdom

提问by Tamás Pap

I want to reload all CSS stylesheets in a html page via javascript, without reloading the page.

我想通过 javascript 重新加载 html 页面中的所有 CSS 样式表,而不重新加载页面。

I need this only while developing to reflect css changes without refreshing the page all time.

我只在开发时需要这个以反映 css 更改,而无需一直刷新页面。

A possible solution is to add a ?id=randomnumbersuffix to the css hrefs with javascript, but I don't want to do that.

一种可能的解决方案是?id=randomnumber使用 javascript 向 css hrefs添加后缀,但我不想这样做。

I want to reload the stylesheetsome way, without changing it's url, and the browser will decide if it needs to load a new version of that css or not (if server responds with a 304 - Not modified).

我想以某种方式重新加载样式表,而不更改它的 url,浏览器将决定是否需要加载该 css 的新版本(如果服务器以 响应304 - Not modified)。

How to accomplish this?

如何做到这一点?

回答by Dillen Meijboom

In plain Javascript:

在纯 Javascript 中:

var links = document.getElementsByTagName("link");

for (var x in links) {
    var link = links[x];

    if (link.getAttribute("type").indexOf("css") > -1) {
        link.href = link.href + "?id=" + new Date().getMilliseconds();
    }
}

In jQuery:

在 jQuery 中:

$("link").each(function() {
    if $(this).attr("type").indexOf("css") > -1) {
        $(this).attr("href", $(this).attr("href") + "?id=" + new Date().getMilliseconds());
    }
});

Make sure you load this function after the DOM tree is loaded.

确保在加载 DOM 树后加载此函数。

回答by ChongFury

First, add an id (if not present) to your stylesheet link tags like so:

首先,向样式表链接标签添加一个 id(如果不存在),如下所示:

<link id="mainStyle" rel="stylesheet" href="style.css" />

Next, in Javascript (also utilizing jQuery) add the following function:

接下来,在 Javascript(也使用 jQuery)中添加以下函数:

function freshStyle(stylesheet){
   $('#mainStyle').attr('href',stylesheet);
}

Lastly, trigger the function on your desired event:

最后,在您想要的事件上触发函数:

$('#logo').click(function(event){
    event.preventDefault();
    var restyled = 'style.css'; 
    freshStyle(restyled);
});

By updating the value of the linked stylesheet, even if it's the same value, you force the client to look again; when it does, it'll see and (re)load the latest file.

通过更新链接样式表的值,即使它是相同的值,您也会强制客户端再次查看;当它这样做时,它会看到并(重新)加载最新的文件。

If you're running into issues with cache, then try appending a random (psuedo) version number to your filename like this:

如果您遇到缓存问题,请尝试将随机(伪)版本号附加到您的文件名,如下所示:

var restyled = 'style.css?v='+Math.random(0,10000);

Hope this helps. Dillen's examples above also work, but you can use this if you want to just target one or a set of stylesheets with minor adjustments.

希望这可以帮助。Dillen 上面的示例也有效,但是如果您只想针对一个或一组样式表进行细微调整,则可以使用它。

回答by Michael Jasper

There are much betterways to accomplish:

很多更好的方法可以实现:

I need this only while developing to reflect css changes without refreshing the page all time.

我只在开发时需要这个以反映 css 更改,而无需一直刷新页面。

One way is to use Grunt.jsto watchfor file changes, and then livereloadthe page.

一种方法是使用Grunt.js监视文件更改,然后实时重新加载页面。

The workflow is like this:

工作流程是这样的:

  • Save css document
  • Grunt watch sees the change
  • live reloads the css on the page
  • 保存 css 文档
  • 咕噜手表看到了变化
  • live 重新加载页面上的 css

This can be chained with other Grunt functions, such as {sass|less|stylus} preprocessor compilation, to create a workflow like this:

这可以与其他 Grunt 函数链接,例如 {sass|less|stylus} 预处理器编译,以创建如下工作流:

  • save a Sass file
  • watch sees change
  • sass is compiled and minified to cdn location
  • new css is loaded onto the page
  • 保存一个 Sass 文件
  • 观察变化
  • sass 被编译并缩小到 cdn 位置
  • 新的 css 加载到页面上

Other front-end automation resources:

其他前端自动化资源:

Video from a Google employee: http://www.youtube.com/watch?v=bntNYzCrzvE

来自 Google 员工的视频:http: //www.youtube.com/watch?v=bntNYzCrzvE

http://sixrevisions.com/javascript/grunt-tutorial-01/

http://sixrevisions.com/javascript/grunt-tutorial-01/

http://aboutcode.net/vogue/

http://aboutcode.net/vogue/

回答by Warlock

It's very simple in the GoogleChrome browser.

在 GoogleChrome 浏览器中非常简单。

Press F12, click the cogwheel at the right bottom corner and select option Disable cache (while DevTools is open).

按 F12,单击右下角的齿轮并选择选项禁用缓存(DevTools 打开时)。

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

回答by Humbertda

An alternative for Grunt would be to use Prepros.

Grunt 的另一种选择是使用Prepros

It also use a file watcher on your project folder, but for all your files. (js, css, php) and reload the page on every change. (+ If this is a small visual change like css, it wont refresh the page, it will make a smooth transition. (Works for colors, positioning, etc.))

它还在您的项目文件夹上使用文件观察器,但适用于您的所有文件。(js, css, php) 并在每次更改时重新加载页面。(+ 如果这是像css这样的小的视觉变化,它不会刷新页面,它会平滑过渡。(适用于颜色、定位等))

Like Grunt, it compile and minify your files, and allow you to make a live preview on a specified url (not only localhost). (There are plenty more of functionalities)

像 Grunt 一样,它编译和缩小您的文件,并允许您在指定的 url(不仅是本地主机)上进行实时预览。(还有很多功能)

Using a special port, it even synchronize eventssuch as clic, mouse wheel, inputs, etc.

使用一个特殊的端口,它甚至可以同步诸如点击、鼠标滚轮、输入等事件