Pau*_*jan 2 javascript scripting jquery include
我正在编写一段代码,要放在任何第三方网站上,并且不知道它将被放入什么环境.我的最终目标是获得徽章
<script src="http://example.com/js/badge.js"></script>
Run Code Online (Sandbox Code Playgroud)
我想在我的徽章代码中使用jQuery来让我的生活更轻松,但我不想在客户端需要另一个包含(在客户端获得任何更新是一件痛苦的事).
这是我能想到的最好的.我不想在我的脚本之前或之后的任何事情受到任何剩余变量或奇怪碰撞的影响.有没有人看到任何问题?
(function() {
function main($) {
// do stuff with $
$(document.body).css("background", "black")
}
// If jQuery exists, save it
var old_jQuery = null;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery.noConflict(true);
}
}
var addLibs = function() {
// Body isn't loaded yet
if (typeof(document.body) == "undefined" || document.body === null) {
setTimeout(addLibs, 100);
return;
}
var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
document.body.appendChild(node);
checkLibs();
}
var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || jQuery("*") === null) {
setTimeout(checkLibs, 100);
return;
}
var new_jQuery = jQuery.noConflict(true);
jQuery = old_jQuery;
main(new_jQuery);
}
addLibs();
})();
Run Code Online (Sandbox Code Playgroud)
我最终选择了http://yourock.paulisageek.com/js/popup.js.请参阅测试(使用控制台日志记录)http://paulisageek.com/tmp/jquery-programatically.html.它不会重置jQuery和$,直到jQuery实际完成加载.有没有无限循环阻止javascript的方法(阻止jQuery加载本身)?
// A namespace for all the internal code
var yourock = {};
// Include JQuery programatically
(function() {
// Don't let the script run forever
var attempts = 30;
// If jQuery exists, save it and delete it to know when mine is loaded
var old_jQuery;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery;
delete jQuery;
}
}
var addLibs = function() {
var head = document.getElementsByTagName("head");
if (head.length == 0) {
if (attempts-- > 0) setTimeout(addLibs, 100);
return;
}
var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
head[0].appendChild(node);
checkLibs();
}
var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || typeof(jQuery) != "function" || jQuery("*") === null) {
if (attempts-- > 0) setTimeout(checkLibs, 100);
return;
}
yourock.jQuery = jQuery.noConflict(true);
if (typeof old_jQuery == "undefined")
jQuery = old_jQuery;
}
addLibs();
})();
Run Code Online (Sandbox Code Playgroud)