当我们在Javascript里需要用到jQuery但又无法判断是否加载过时,可以通过下面的方法来自动判断并加载jQuery,代码如下:
代码如下 | 复制代码 |
function getScript(url, success) { var script = document.createElement('script'); script.src = url; var head = document.getElementsByTagName('head')[0], done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { done = true; // callback function provided as param success(); script.onload = script.onreadystatechange = null; head.removeChild(script); }; }; head.appendChild(script); }; if (typeof jQuery == 'undefined') { |
loadScript异步加载脚本
一、语法:
loadScript(url[,callback])
或者
loadScript(settings)
二、settings支持的参数:
url:脚本路径
async:是否异步,默认false(HTML5)
charset:文件编码
cache:是否缓存,默认为true
success:加载成功后执行的函数,优先执行callback。
三、调用举例:
代码如下 | 复制代码 |
//loadScript(url[,callback]) loadScript(“http://code.jquery.com/jquery.js”); loadScript(“http://code.jquery.com/jquery.js”,function(){ console.log(1) }); //loadScript(settings) loadScript({“url”:”http://code.jquery.com/jquery.js”,”async”:false,”charset”:”utf-8〃,”cache”:false}); loadScript({“url”:”http://code.jquery.com/jquery.js”,”async”:false,”charset”:”utf-8〃,”success”:function(){ console.log(2) }}); //或者你可以酱紫: //loadScript(settings[,callback]) loadScript({“url”:”http://code.jquery.com/jquery.js”,”async”:false,”charset”:”utf-8〃},function(){ console.log($) }); |
四、源代码:
代码如下 | 复制代码 |
function loadScript(url,callback) { var head = document.head || document.getElementsByTagName(“head”)[0] || document.documentElement, script, options, if (typeof url === “object”) { |