更改css链接并等待加载新的css

change css link and wait till new css is loaded

本文关键字:css 加载 链接 更改 等待      更新时间:2023-09-26

我想知道是否可以更改加载文档的样式表链接,然后等待加载新的css,然后运行适当的js代码

感谢您的任何建议

html:

<link id="mystylesheet" href="/path/to/css.css" />

代码:

$("#mystylesheet").load(function(){
  //Your javascript
}).attr("href", "/new/path/to/css.css");

这将替换当前的CSS,并在获取新的CSS文件后执行.load()处理程序中的任何代码。

@ahren几乎是正确的。然而,在大多数移动设备上,通过动态更改链接元素上的href来完成css文件加载时使用回调似乎不起作用。

相反,请尝试使用load将样式直接注入到样式元素中。。最终被包括移动浏览器在内的大多数现代浏览器所支持

更新以包括对IE 8-的支持;注意,这需要在css中注入一个伪规则,以验证何时加载css(在这种情况下,使用body{ready:true;})

css

body {ready:true;}
...

html

<style id="your-style-element"></style>

javascript

if (document.createStyleSheet) {
    //Wait for style to be loaded
    var wait = setInterval(function(){
      //Check for the style to be applied to the body
      if($('body').css('ready') === 'true') {
        clearInterval(wait);
        //CSS ready
      }
    }, 300);
    document.createStyleSheet(url);
} else {
    //Dynamically load the css for this doc
    $("#your-style-element").load(url,function(){
       //CSS ready
    });
}

试试这个男人:http://forum.jquery.com/topic/loading-stylesheets-on-the-fly

或:http://www.rickardnilsson.net/post/2008/08/02/Applying-stylesheets-dynamically-with-jQuery.aspx使用jQuery 更改样式表

希望符合:) 的原因

代码

var link = $("<link>");
link.attr({
        type: 'text/css',
        rel: 'stylesheet',
        href: <your CSS file url>
});
$("head").append( link ); 

您可以尝试我专门为这种情况编写的插件。

不确定jQuery.load()方法,它似乎不是跨浏览器的。只有IE支持链接元素上的onload=""事件,afaik。

下面是我写的一个要点,它只适用于47 LOC:

https://gist.github.com/aleclarson/ac6456c75edae9fe9d9b6938142a065b

它使用requestAnimationFrame在每个帧上检查document.styleSheets,直到加载了每个给定的URL片段。

示例:

const styles = require('./styles')
const promise = styles.onLoad('foo.css', 'bar.css')
promise.then(() => console.log('Styles loaded!'))

纯javascript!

TeaCoder在https://stackoverflow.com/a/35644406/20774.

基本上使用元素onload方法,并在那里放置您希望在样式加载后发生的逻辑。

使用内置DOM功能是一种很好的方法,但回调语法有点尴尬。以下是我如何使用Promises:

const createOnLoadPromise = (htmlElement) =>
  new Promise((resolve) => {
    htmlElement.onload = resolve;
  });
const link1 = document.head.appendChild(createStyleLink(href1));
const link2 = document.head.appendChild(createStyleLink(href2));
await Promise.all([
  createOnLoadPromise(link1),
  createOnLoadPromise(link2),
]);
// do whatever you need to do after the await