javascript实现动态导入js与css等静态资源文件的方法
本文实例讲述了javascript实现动态导入js与css等静态资源文件的方法。分享给大家供大家参考。具体实现方法如下:
/** * 动态导入静态资源文件js/css */ var $import = function(){ return function(rId, res, callback){ if(res && 'string' == typeof res){ if(rId){ if($($('#' + rId), $('head')).length>0){ return; } } //加载资源文件 var sType = res.substring(res.lastIndexOf('.') + 1); // 支持js/css if(sType && ('js' == sType || 'css' == sType)){ var isScript = (sType == 'js'); var tag = isScript ? 'script' : 'link'; var head = document.getElementsByTagName('head')[0]; // 创建节点 var linkScript = document.createElement(tag); linkScript.type = isScript ? 'text/javascript' : 'text/css'; linkScript.charset = 'UTF-8'; if(!isScript){ linkScript.rel = 'stylesheet'; } isScript ? linkScript.src = res : linkScript.href = res; if(callback && 'function' == typeof callback){ if (linkScript.addEventListener){ linkScript.addEventListener('load', function(){ callback.call(); }, false); } else if (linkScript.attachEvent) { linkScript.attachEvent('onreadystatechange', function(){ var target = window.event.srcElement; if (target.readyState == 'complete') { callback.call(); } }); } } head.appendChild(linkScript); } } }; }();
希望本文所述对大家的javascript程序设计有所帮助。
相关推荐
NARUTOLUOLUO 2020-08-03
qiupu 2020-11-04
多读书读好书 2020-11-03
RedCode 2020-10-28
jiedinghui 2020-10-25
Ladyseven 2020-10-22
hellowzm 2020-10-12
zuncle 2020-09-28
Ladyseven 2020-09-11
jiedinghui 2020-09-07
xiaohuli 2020-09-02
葉無聞 2020-09-01
impress 2020-08-26
ThikHome 2020-08-24
nicepainkiller 2020-08-20
hellowzm 2020-08-18