Home  >  Article  >  Web Front-end  >  判断在css加载完毕后执行后续代码示例_javascript技巧

判断在css加载完毕后执行后续代码示例_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:37:301367browse

最近在写项目的framework,写个JQueryMessageBox的类,以使用jquery ui中的dialog()来显示消息框,为了使方法方便调用,便加入了自动判断页面是否加入了ui.js和ui.css,代码如下:

//如果没有包含ui.js,则引用 
if ($('script[src$=""jquery-ui-1.8.11.custom.min.js""]').length == 0) {{ 
$(""<script src='/js/jquery-ui-1.8.11.custom.min.js' type='text/javascript' />"").appendTo('head'); 
}} 
//如果没有加载css,则加载 
if ($('link[ref$=""jquery-ui-1.8.14.custom.css""]').length == 0) {{ 
$('<link href=""/css/jquery-ui-1.8.14.custom.css"" rel=""stylesheet"" type=""text/css"" />').appendTo('head'); 

//dialog() script 
}}

但CSS代码不会立即加载下来,于是在显示dialog的时候则不会有样式(在IE9下可以,因为在IE9下CSS即使后下载下来,也会重新绘制页面元素,而IE8则不会).解决此问题的方法,可以使用ajax,当css加载完毕后,再显示dialog,这样就可以带着样式显示出来了,代码如下:

if ($('link[ref$=""jquery-ui-1.8.14.custom.css""]').length == 0) { 
$.ajax({ 
url: '/css/jquery-ui-1.8.14.custom.css', 
success: function(data) { 
//创建一个style元素,并追加到head中 
//替换其中images的路径 
$('<style type="text/css">' + data.replace(/url\(images/g, 'url(/css/images') + '</style>').appendTo('head'); 
//dialog() script; 
} 
}); 
} 
else { 
//dialog() script; 
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn