我试图使用javascript动态加载一个css文件,不能使用任何其他的js库(例如jQuery)。
css文件加载,但我似乎无法得到一个回调工作。以下是我正在使用的代码
- var callbackFunc = function(){
- console.log('file loaded');
- };
- var head = document.getElementsByTagName( "head" )[0];
- var fileref=document.createElement("link");
- fileref.setAttribute("rel","stylesheet");
- fileref.setAttribute("type","text/css");
- fileref.setAttribute("href",url);
- fileref.onload = callbackFunc;
- head.insertBefore( fileref,head.firstChild );
使用以下代码添加脚本标签来加载js文件可以起作用并触发回调:
- var callbackFunc = function(){
- console.log('file loaded');
- };
- var script = document.createElement("script");
- script.setAttribute("src",url);
- script.setAttribute("type","text/javascript");
- script.onload = callbackFunc ;
- head.insertBefore( script,head.firstChild );
我在这里做错了吗?可以帮助我实现这一点的任何其他方法将不胜感激?
解决方法
不幸的是,大多数现代浏览器中的样式表都没有负载支持。有一个解决方案,我发现一些谷歌。
引用自:http://thudjs.tumblr.com/post/637855087/stylesheet-onload-or-lack-thereof
基础
最基本的实现可以在一个简单的30行框架中独立完成 – JavaScript代码:
- function loadStyleSheet( path,fn,scope ) {
- var head = document.getElementsByTagName( 'head' )[0],// reference to document.head for appending/ removing link nodes
- link = document.createElement( 'link' ); // create the link node
- link.setAttribute( 'href',path );
- link.setAttribute( 'rel','stylesheet' );
- link.setAttribute( 'type','text/css' );
- var sheet,cssRules;
- // get the correct properties to check for depending on the browser
- if ( 'sheet' in link ) {
- sheet = 'sheet'; cssRules = 'cssRules';
- }
- else {
- sheet = 'styleSheet'; cssRules = 'rules';
- }
- var interval_id = setInterval( function() { // start checking whether the style sheet has successfully loaded
- try {
- if ( link[sheet] && link[sheet][cssRules].length ) { // SUCCESS! our style sheet has loaded
- clearInterval( interval_id ); // clear the counters
- clearTimeout( timeout_id );
- fn.call( scope || window,true,link ); // fire the callback with success == true
- }
- } catch( e ) {} finally {}
- },10 ),// how often to check if the stylesheet is loaded
- timeout_id = setTimeout( function() { // start counting down till fail
- clearInterval( interval_id ); // clear the counters
- clearTimeout( timeout_id );
- head.removeChild( link ); // since the style sheet didn't load,remove the link node from the DOM
- fn.call( scope || window,false,link ); // fire the callback with success == false
- },15000 ); // how long to wait before failing
- head.appendChild( link ); // insert the link node into the DOM and start loading the style sheet
- return link; // return the link node;
- }
这将允许您使用onload回调函数加载样式表,如下所示:
- loadStyleSheet( '/path/to/my/stylesheet.css',function( success,link ) {
- if ( success ) {
- // code to execute if the style sheet was loaded successfully
- }
- else {
- // code to execute if the style sheet Failed to successfully
- }
- } );
或者如果你想要回调来维护它的范围/上下文,你可以做一些这样的事情:
- loadStyleSheet( '/path/to/my/stylesheet.css',this.onComplete,this );