栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

基础

最基本的实现可以通过大约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 ) {      // pre to execute if the style sheet was loaded successfully   }   else {      // pre to execute if the style sheet failed to successfully   }} );

或者,如果您希望回调保持其范围/上下文,则可以执行以下操作:

loadStyleSheet( '/path/to/my/stylesheet.css', this.onComplete, this );


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668691.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号