2012年8月24日星期五

异步加载外部Javascript

异步加载外部Javascript

 1 $.extend({ 2         loadScript : function (url, data, callback) { 3             if ($.isFunction(data)) { 4                 callback = data; 5                 data = null; 6             } 7             if (data != null) { 8                 var urlInfo = url.match(/^([^?#]+)\?*([^#]*)#?(.*)$/); 9                 url = urlInfo[1];10                 var query = $.trim(urlInfo[2]);11                 var fragment = $.trim(urlInfo[3]);12                 if (typeof data === 'object') {13                     data = $.param(data);14                 }15                 if (typeof data === 'string') {16                     query += (query == '' ? data : ("&" + data));17                 }18                 query === '' || (url += ('?' + query));19                 fragment === '' || (url += ('#' + fragment));20             }21             22             var script = document.createElement("script");23             script.type = "text/javascript";24             script.src = url;25             script.onload = script.onreadystatechange = function () {26                 if (!document.all || document.all && this.readyState == "loaded") {27                     if ($.isFunction(callback)) {28                         callback();29                     }30                 }31             }32             document.getElementsByTagName("head")[0].appendChild(script);33             delete script;34         }35     });

TAG: