使用javascript重新加载CSS样式表 [英] Reload CSS stylesheets with javascript

查看:107
本文介绍了使用javascript重新加载CSS样式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我想以某种方式重新载入样式表,而不更改网址,浏览器将决定是否需要载入新版本(如果服务器响应 304 - 未修改)。

I want to reload the stylesheet some 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).

如何完成? / p>

How to accomplish this?

推荐答案

在纯JavaScript中:

In plain 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();
    }
}

在jQuery中:

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

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

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

这篇关于使用javascript重新加载CSS样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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