一旦jQuery插件加载就做一些事情
我正在动态地将jQuery
和jQuery UI
加载到页面中,我需要知道jQuery UI
何时成功扩展了jQuery
。
目前我正在使用加载jQuery UI
的脚本元素的readystate
来触发我的代码的运行,但我认为那时脚本已加载,但jQuery UI
尚未正确初始化。
在定义$.ui
之前,是唯一的选择吗?
这是我目前正在努力解决的代码:
(load_ui = (callback) -> script2 = document.createElement("script") script2.type = "text/javascript" script2.src = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.js" script2.onload = script2.onreadystatechange = -> console.log 'readystate:', @readystate if @readystate == "loaded" or @readystate == "complete" console.log "jquery ui is loaded" callback ($ = window.jQuery).noConflict(1), done = 1 $(script,script2).remove() document.documentElement.childNodes[0].appendChild script2 console.log 'jquery ui script element appended to page' (window, document, req_version, callback, $, script, done, readystate) -> if not ($ = window.jQuery) or req_version > $.fn.jquery or callback($) console.log "begin loading jquery" script = document.createElement("script") script.type = "text/javascript" script.src = "http://ajax.googleapis.com/ajax/libs/jquery/" + req_version + "/jquery.min.js" script.onload = script.onreadystatechange = -> if not done and (not (readystate = @readyState) or readystate == "loaded" or readystate == "complete") console.log "jquery is loaded, now loading jquery ui" load_ui(callback) document.documentElement.childNodes[0].appendChild script console.log 'jquery script element appended to page' ) window, document, "1.6.1", ($, L) -> console.log $ console.log $.ui.version
由于某种原因,jquery ui脚本元素的readystate只返回undefined。
我认为这将完全符合您的需求,可以根据需要添加更多依赖项。
(function () { function getScript(url, success) { var script = document.createElement('script'); script.src = url; var head = document.getElementsByTagName('head')[0]; var completed = false; script.onload = script.onreadystatechange = function () { if (!completed && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { completed = true; success(); script.onload = script.onreadystatechange = null; head.removeChild(script); } }; head.appendChild(script); } getScript("Scripts/jquery-1.6.1.js", function () { getScript("Scripts/jquery-ui-1.8.11.js", function () { alert($.ui); }); }); })();
经过 IE7,IE8,IE9,Firefox,Safari,Chrome和Opera的测试
我在一些项目中使用此代码以确保某些脚本按顺序运行。 它没有在IE上工作(我没有时间调试),但在其他一切工作正常。
var node = document.createElement("script"); $.extend(node, { type: 'text/javascript', charset: 'utf-8', async: false, defer: true, src: /*...*/ }); $(node).bind('load', loadedCallback); $('head')[0].appendChild(node);