首页 > 编程 > JavaScript > 正文

动态加载js、css的实例代码

2019-11-20 09:54:38
字体:
来源:转载
供稿:网友

一、原生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的实例代码,希望对大家有所帮助!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表