首页 > 代码库 > 动态加载javascript增强版
动态加载javascript增强版
我们经常使用动态加载Javascript,写个函数很容易现实,之前也写过一个函数,不过当加载多个JS时,只能根据浏览器返回的顺序来先后加载,这肯定不是我们想要的,现在使用了一下技巧,当加载多个JS时,能按照我们的顺序加载:
Js代码
- /*
- Name:动态加载JS
- Author:kingwell Leng
- Date : 2013/4/21
- E-mail: jinhua.leng##gmail.com
- */
- function getScript(obj, callback) {
- var arr = obj,
- timeout,
- str = typeof obj === ‘string‘;
- function add() {
- var script = document.createElement("script");
- header = document.getElementsByTagName("head")[0];
- script.src = str ? obj : arr[0];
- script.type = "text/javascript";
- if (str) {
- if (script.readyState) {
- script.onreadystatechange = function () {
- if (script.readyState === ‘loaded‘ || script.readyState === ‘complete‘) {
- script.onreadystatechange = null;
- callback && callback();
- }
- };
- } else {
- script.onload = function () {
- callback && callback();
- };
- }
- } else {
- if (arr.length >= 1) {
- if (script.readyState) {
- script.onreadystatechange = function () {
- if (script.readyState === ‘loaded‘ || script.readyState === ‘complete‘) {
- script.onreadystatechange = null;
- arr.shift();
- timeout = setTimeout(add, 1);
- }
- };
- } else {
- script.onload = function () {
- arr.shift();
- timeout = setTimeout(add, 1);
- };
- }
- } else {
- clearTimeout(timeout);
- callback && callback();
- }
- }
- header.appendChild(script);
- }
- add();
- }
/* Name:动态加载JS Author:kingwell Leng Date : 2013/4/21 E-mail: jinhua.leng##gmail.com*/function getScript(obj, callback) { var arr = obj, timeout, str = typeof obj === ‘string‘; function add() { var script = document.createElement("script"); header = document.getElementsByTagName("head")[0]; script.src = http://www.mamicode.com/str ? obj : arr[0];"text/javascript"; if (str) { if (script.readyState) { script.onreadystatechange = function () { if (script.readyState === ‘loaded‘ || script.readyState === ‘complete‘) { script.onreadystatechange = null; callback && callback(); } }; } else { script.onload = function () { callback && callback(); }; } } else { if (arr.length >= 1) { if (script.readyState) { script.onreadystatechange = function () { if (script.readyState === ‘loaded‘ || script.readyState === ‘complete‘) { script.onreadystatechange = null; arr.shift(); timeout = setTimeout(add, 1); } }; } else { script.onload = function () { arr.shift(); timeout = setTimeout(add, 1); }; } } else { clearTimeout(timeout); callback && callback(); } } header.appendChild(script); } add();}
调用:
Js代码
- getScript([‘http://code.jquery.com/jquery-1.9.1.min.js‘,‘js1.js‘, ‘js2.js‘, ‘js3.js‘, ‘js4.js‘], function () {
- alert(‘我是按顺序加载啦‘);
- });
getScript([‘http://code.jquery.com/jquery-1.9.1.min.js‘,‘js1.js‘, ‘js2.js‘, ‘js3.js‘, ‘js4.js‘], function () { alert(‘我是按顺序加载啦‘);});
现在是按照我们写代码的顺序加载啦...
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。