一、原生js:
/** * 加載js和css文件 * @param jsonData.path 前綴路徑 * @param jsonData.url 需要加載的js路徑或css路徑 * @param jsonData.type 需要加載的類型 js或css */ function loadWriteFiles(jsonData) { jsonData.path = jsonData.path != undefined ? jsonData.path : ""; if(jsonData.type == "js") { document.writeln("<script type='text/javascript' src='"+ jsonData.path + jsonData.url+"'></script>"); } else if(jsonData.type == "css") { document.writeln("<link rel='stylesheet' href='"+jsonData.path + jsonData.url+"' type='text/css' />"); } } /** * 加載js或css到head中 * @param jsonData.path 前綴路徑 * @param jsonData.url 需要加載的js路徑或css路徑 * @param jsonData.type 需要加載的類型 js或css */ function loadFilesToHead(jsonData) { jsonData.path = jsonData.path != undefined ? jsonData.path : ""; if(jsonData.type == "js") { var _js = document.createElement("script"); _js.setAttribute("type", "text/javascript"); _js.setAttribute("src", jsonData.path + jsonData.url); _js.onload = _js.onreadystatechange=function(){ if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){ if("function" == typeof(jsonData["callback"]) && jsonData["callback"]){ jsonData["callback"].call(this); } } _js.onload=_js.onreadystatechange=null; } document.getElementsByTagName("head")[].appendChild(_js);//追加到head標簽內 } else if(jsonData.type == "css") { var _css = document.createElement("link"); _js.setAttribute("type", "text/css"); _css.setAttribute("rel", "stylesheet"); _css.setAttribute("href", jsonData.path + jsonData.url); document.getElementsByTagName("head")[].appendChild(_css);//追加到head標簽內 } }
二、jquery版本:
采用deferred對象返回結果
var uiLoad = uiLoad || {}; (function($, $document, uiLoad) { "use strict"; var loaded = [], promise = false, deferred = $.Deferred(); uiLoad.load = function (srcs) { srcs = $.isArray(srcs) ? srcs : srcs.split(/\s+/); if(!promise){ promise = deferred.promise(); } $.each(srcs, function(index, src) { promise = promise.then( function(){ return src.indexOf('.css') >= ? loadCSS(src) : loadScript(src); } ); }); deferred.resolve(); return promise; }; var loadScript = function (src) { if(loaded[src]) return loaded[src].promise(); var deferred = $.Deferred(); var script = $document.createElement('script'); script.src = src; script.onload = function (e) { deferred.resolve(e); }; script.onerror = function (e) { deferred.reject(e); }; $document.body.appendChild(script); loaded[src] = deferred; return deferred.promise(); }; var loadCSS = function (href) { if(loaded[href]) return loaded[href].promise(); var deferred = $.Deferred(); var style = $document.createElement('link'); style.rel = 'stylesheet'; style.type = 'text/css'; style.href = href; style.onload = function (e) { deferred.resolve(e); }; style.onerror = function (e) { deferred.reject(e); }; $document.head.appendChild(style); loaded[href] = deferred; return deferred.promise(); } })(jQuery, document, uiLoad);
以上所述是小編給大家介紹的動態加載js、css的實例代碼,希望對大家有所幫助!