当前位置: 首页 > 面试题库 >

使用带回调的JavaScript动态加载CSS文件而不使用jQuery

杭志泽
2023-03-14
问题内容

我正在尝试使用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 );

我在这里做错什么了吗?还有其他方法可以帮助我实现这一目标吗?


问题答案:

不幸的是,大多数现代浏览器都不支持样式表的加载。我发现有一点谷歌搜索解决方案

基础

最基本的实现可以通过大约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 );


 类似资料:
  • 本文向大家介绍使用javaScript动态加载Js文件和Css文件,包括了使用javaScript动态加载Js文件和Css文件的使用技巧和注意事项,需要的朋友参考一下 JS动态加载CSS 在可换主题的界面中具有很重要的意义,用户可以根据自己的浏览习惯选择自己喜欢的页面显示方式,下面详细说明。 希望下面的方法对你有帮助。 (1)使用JavaScript动态加载Js文件 (2)使用JavaScript

  • 问题内容: 是否可以使用Javascript将CSS样式表导入html页面?如果是这样,怎么办? 附言:JavaScript将托管在我的网站上,但我希望用户能够放入其网站的标签,并且它应该能够将托管在我的服务器上的CSS文件导入当前网页。(css文件和javascript文件都将托管在我的服务器上)。 问题答案: 这是这样做的“老派”方法,希望可以在所有浏览器上使用。从理论上讲,不幸的是,您将使用

  • 本文向大家介绍IE8中使用javascript动态加载CSS的解决方法,包括了IE8中使用javascript动态加载CSS的解决方法的使用技巧和注意事项,需要的朋友参考一下 众所周知做前端开发的都恨不得踹IE开发者几脚,IE开发者名声之差不低于GFW开发者,昧着良心搞坏市场,人人得而诛之,但是在中国这些地方市场占有率摆在那里,没办法只能向现实低头。 最近我们产品需要在浏览器里动态载入一段CSS,

  • 问题内容: 如何可靠,动态地加载JavaScript文件?这将用于实现模块或组件,该模块或组件在“初始化”时将根据需要动态加载所有需要的JavaScript库脚本。 使用该组件的客户端不需要加载实现该组件的所有库脚本文件(并将标记手动插入其网页),只需加载“主”组件脚本文件即可。 主流JavaScript库如何做到这一点(原型,jQuery等)? 这些工具是否将多个JavaScript文件合并到脚

  • 问题内容: 我有一个非常大的javascript文件,仅当用户单击某个按钮时才想加载。我正在使用jQuery作为框架。有内置的方法或插件可以帮助我做到这一点吗? 更多详细信息:我有一个“添加注释”按钮,该按钮应该加载TinyMCE javascript文件(我已经将所有TinyMCE东西都煮成了一个JS文件),然后调用tinyMCE.init(…)。 我不想在初始页面加载时加载它,因为不是每个人都

  • 本文向大家介绍使用jquery动态加载js文件的方法,包括了使用jquery动态加载js文件的方法的使用技巧和注意事项,需要的朋友参考一下 方法很简单,这里就不多废话了,直接奉上代码: 小伙伴们如果有什么疑问就在下面留言吧,大家共同进步。