更改css链接并等待加载新的css
change css link and wait till new css is loaded
我想知道是否可以更改加载文档的样式表链接,然后等待加载新的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
- 当我更改Joomla时,它仍然从旧域加载CSS和Javascript
- Wordpress插件根据需要加载js和css
- 如何使用谷歌页面速度CSS加载脚本延迟多个CSS文件
- 我需要强制 IE 6、7 和 8 等到 CSS 加载后再渲染页面
- 如何将css加载程序仅应用于内容的一个特定部分
- Phonegap-创建CSS加载屏幕
- Ajax 使用 CSS 加载页面
- 当html内容包含使用css加载的图像时,ng绑定html不起作用
- 为什么当路径正确时,图像无法从CSS加载,而当直接输入URL时加载
- 正在将不同的css加载到IE
- 使用Angular 1.2和Animate.css加载动画
- 实现Webpack css加载器时遇到问题,编译错误
- 当css加载到body中时,Jquery Colorbox会破裂,这是一个可能的修复
- 在css加载之后、图片下载之前运行代码
- 我应该通过JS或CSS加载响应式设计
- 在asp.net回发期间启动javascript(以显示css加载器/旋转器)
- 如何在页面加载时显示CSS加载器
- Ruby on Rails -登录或注销后的redirect_to不做与新页面相关的ajax/js/css加载
- 处理CSS加载失败
- 奇怪的CSS加载