我们经常使用动态加载Javascript,写个函数很容易现实,之前也写过一个函数,不过当加载多个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 = 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(); }
调用:
- 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(‘我是按顺序加载啦‘); });
现在是按照我们写代码的顺序加载啦...