[英]jQuery event that triggers after CSS is loaded?
我的页面上有几个链接(在<div id="theme-selector">
)允许您更改 CSS 样式表:
$('#theme-selector a').click(function(){
var path = $(this).attr('href');
$('head link').remove();
$('head').append('<link type="text/css" href="'+path+'" rel="stylesheet" />');
return false;
});
现在,在更改页面样式后,我想使用以下代码(我将其放在$('head').append
调用之后)获取新的背景颜色:
var bgcolor = $('body').css('background-color');
alert(bgcolor);
我认为问题是浏览器下载新样式表需要一些时间,有时我的警报消息中会出现旧的背景颜色。 是否有一些我可以绑定的事件只会在页面上加载所有样式表后才提醒我?
目前,我能想到的就是使用setTimeout(function(){}, 5000);
这不是很好,因为如果加载页面上的所有 CSS 需要更长/更短的时间怎么办。
如果我需要澄清任何事情,请告诉我,我可以提供更多代码。
您可以使用 AJAX 调用检索样式表的内容,并将其插入到内联样式块中,而不是创建一个新的链接元素并将其附加到头部。 这样,您就可以使用 jQuery 的“完成”回调来触发您的支票。
$('#theme-selector a').click(function(){
var path = $(this).attr('href');
$.get(path, function(response){
//Check if the user theme element is in place - if not, create it.
if (!$('#userTheme').length) $('head').append('<style id="userTheme"></style>');
//populate the theme element with the new style (replace the old one if necessary)
$('#userTheme').text(response);
//Check whatever you want about the new style:
alert($('body').css('background-color'));
});
});
我还没有真正测试过这段代码,所以可能会有一些语法错误,但逻辑应该足够合理。
可以监视与 url 关联的任何元素的 load 事件,这在加载 css 样式表时对您不起作用吗? http://api.jquery.com/load-event/
尝试这样的事情:
var path = $(this).attr('href');
$('head link').remove();
var styleSheet = $('<link type="text/css" href="'+path+'" rel="stylesheet" />');
styleSheet.load(function(){alert("Loaded");});
$('head').append(styleSheet);
编辑:正如下面所指出的,这只适用于 IE,谁会想到?
var cssLoaded = function()
{
alert($('body').css('background-color'));
};
$('#theme-selector a').click(function(){
var path = $(this).attr('href');
$('head link').remove();
$('head').append('<link onload="cssLoaded();" type="text/css" href="'+path+'" rel="stylesheet" />');
return false;
});
在 Chrome 28、IE 10、FF22 中成功测试
您可以使用lazyload (jQuery 插件)来加载 css 文件。 它能够在包含文件时调用函数。
例子:
// Load a CSS file and pass an argument to the callback function.
LazyLoad.css('foo.css', function (arg) {
// put your code here
});
在100% 确定外部工作表已延迟加载和渲染后,来到这里寻找一种删除关键 CSS(元素)的方法。 这将允许我在多个项目中全局使用通用但视觉上令人愉悦的关键内部 CSS。 由于某些关键样式在视觉上与延迟加载的样式相反,因此需要覆盖(太多工作)或删除它们。 这就是我想要的,简而言之:
100% 有效的解决方案(可能不受欢迎)是使用setInterval(); 延迟加载二级CSS后,定期检查是否真正应用了二级CSS独有的样式。 然后我可以删除关键的 CSS(或者我想做的任何事情......)。
我在 Codepen 上创建了一个带有评论的现场演示: https ://codepen.io/Marko36/pen/YjzQzd 和博客文章中的一些信息: 在 CSS 加载后触发 Javascript/jQuery 事件。
var CSSloadcheck = setInterval(function () {
if ($('body').css('opacity') != 1) {
//when opacity is set to 0.99 by external sheet
$('style#critical').remove();
clearInterval(CSSloadcheck);
}
}, 100);
您可以简单地继续检查背景颜色是否仍然相同,然后在它发生变化时执行您的操作。
oldbackground=getbackground()
function checkbackground(){
if(oldbackground!=getbackground()){
oldbackground=getbackground()
//Do your thing
}
}
setInterval(checkbackground,100)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.