這篇文章主要介紹了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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選