动态加载js和css成熟解决方案

认真写好每一篇,愉悦自己,也方便他人
推荐第一种,兼容性好方便速度快

为什么要用这个?
假如你不是用前端框架,而是原生的html+css+js手撸的模板的话,那么你肯定会用到非常多的插件,会引入非常多的js文件这样会显得非常不舒服,你可以通过方案一一次性引入,或者有时候需要动态加载css和js的特殊情况也可以用到

方案一:第三方解决方案lazyload

这个是好几年年前的东西了也有1到2K的star,不过作者已经不维护,作者说他们项目已经不使用这个,可能都是去使用前端的其它框架开发了,但是并不影响我们使用它

lazyload地址
原版有很多注释且也没有提供压缩版这里贴一个压缩版

LazyLoad=function(e){function t(t,n){var s,c=e.createElement(t);for(s in n)n.hasOwnProperty(s)&&c.setAttribute(s,n[s]);return c}function n(e){var t,n,s=i[e];s&&(t=s.callback,n=s.urls,n.shift(),u=0,n.length||(t&&t.call(s.context,s.obj),i[e]=null,f[e].length&&c(e)))}function s(){var t=navigator.userAgent;o={async:!0===e.createElement("script").async},(o.webkit=/AppleWebKit\//.test(t))||(o.ie=/MSIE|Trident/.test(t))||(o.opera=/Opera/.test(t))||(o.gecko=/Gecko\//.test(t))||(o.unknown=!0)}function c(c,u,h,g,d){var y,p,b,k,m,v,j=function(){n(c)},w="css"===c,T=[];if(o||s(),u)if(u="string"==typeof u?[u]:u.concat(),w||o.async||o.gecko||o.opera)f[c].push({urls:u,callback:h,obj:g,context:d});else for(y=0,p=u.length;y<p;++y)f[c].push({urls:[u[y]],callback:y===p-1?h:null,obj:g,context:d});if(!i[c]&&(k=i[c]=f[c].shift())){for(l||(l=e.head||e.getElementsByTagName("head")[0]),m=k.urls.concat(),y=0,p=m.length;y<p;++y)v=m[y],w?b=o.gecko?t("style"):t("link",{href:v,rel:"stylesheet"}):(b=t("script",{src:v}),b.async=!1),b.className="lazyload",b.setAttribute("charset","utf-8"),o.ie&&!w&&"onreadystatechange"in b&&!("draggable"in b)?b.onreadystatechange=function(){/loaded|complete/.test(b.readyState)&&(b.onreadystatechange=null,j())}:w&&(o.gecko||o.webkit)?o.webkit?(k.urls[y]=b.href,r()):(b.innerHTML='@import "'+v+'";',a(b)):b.onload=b.onerror=j,T.push(b);for(y=0,p=T.length;y<p;++y)l.appendChild(T[y])}}function a(e){var t;try{t=!!e.sheet.cssRules}catch(s){return u+=1,void(u<200?setTimeout(function(){a(e)},50):t&&n("css"))}n("css")}function r(){var e,t=i.css;if(t){for(e=h.length;--e>=0;)if(h[e].href===t.urls[0]){n("css");break}u+=1,t&&(u<200?setTimeout(r,50):n("css"))}}var o,l,i={},u=0,f={css:[],js:[]},h=e.styleSheets;return{css:function(e,t,n,s){c("css",e,t,n,s)},js:function(e,t,n,s){c("js",e,t,n,s)}}}(this.document);

//动态加载 CSS 文件
LazyLoad.css(['css/bootstrap.min.css']);
//动态加载 JS 文件
LazyLoad.js(['js/jquery.min.js','js/bootstrap.min.js']);

方案二:自己动手

次方法无法控制先后加载顺序(根据情况使用)

var dynamicLoading = {
  css: function(path){
  if(!path || path.length === 0){
  throw new Error('argument "path" is required !');
  }
  var head = document.getElementsByTagName('head')[0];
  var link = document.createElement('link');
  link.href = path;
  link.rel = 'stylesheet';
  link.type = 'text/css';
  head.appendChild(link);
  },
  js: function(path){
  if(!path || path.length === 0){
  throw new Error('argument "path" is required !');
  }
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.src = path;
  script.type = 'text/javascript';
  head.appendChild(script);
  }
  }

//动态加载 CSS 文件
dynamicLoading.css("test.css");

//动态加载 JS 文件
dynamicLoading.js("test.js");

方案三:判断加载状态

var loadscript = {
    $$: function (id) {
        return document.getElementById(id)
    },
    tag: function (element) {
        return document.getElementsByTagName(element)
    },
    ce: function (element) {
        return document.createElement(element)
    },
    js: function (url, callback) {
        var s = loadscript.ce('script')
        s.type = 'text/javascript'
        s.src = url
        if (document.documentMode == 10 || document.documentMode == 9) {
            s.onerror = s.onload = loaded
        } else {
            s.onreadystatechange = ready
            s.onerror = s.onload = loaded
        }
        loadscript.tag('head')[0].appendChild(s)

        function ready() {
            /*IE7.0/IE10.0*/
            if (s.readyState == 'loaded' || s.readyState == 'complete') {
                callback()
            }
        }

        function loaded() {
            /*chrome/IE10.0*/
            callback()
        }
    }
}

使用方式

loadscript.js('static/js/jquery.min.js', function () {
    loadscript.js('static/js/bootstrap.min.js', function () {
        loadscript.js('lib/bootstrap-notify/bootstrap-notify.min.js', function () {
            loadscript.js('static/js/main.js', function () {})
        })
    })
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值