有没有办法等到jquery库加载到我们执行其他外部javascript文件,所以等待这个完全加载:
<script type="text/javascript" src="jquery-1.7.2.js"></script>
然后加载其他文件,例如:
<script type="text/javascript" src="campaign_winter_2013/bg_outerwear/js/main.js"></script>
<script type="text/javascript" src="campaign_winter_2013/bg_outerwear/js/mousePosSlide.js"></script>
问题是我在一个平台中集成代码,并且在我的脚本之前加载了jquery库。
答案 0 :(得分:6)
您可以先加载jquery库,然后调用JS文件中定义的方法。以下代码对我有用。
<body>
function loadJQuery(){
var waitForLoad = function () {
if (typeof jQuery != "undefined") {
console.log("jquery loaded..");
// invoke any methods defined in your JS files to begin execution
} else {
console.log("jquery not loaded..");
window.setTimeout(waitForLoad, 500);
}
};
window.setTimeout(waitForLoad, 500);
}
window.onload = loadJQuery;
</body>
答案 1 :(得分:1)
检查一下:
https://jsfiddle.net/neohunter/ey2pqt5z/
它将创建一个假的jQuery对象,允许你使用jquery的onload方法,并且只要加载jquery就会执行它们。
它并不完美。
// This have to be on <HEAD> preferibly inline
var delayed_jquery = [];
jQuery = function() {
if (typeof arguments[0] == "function") {
jQuery(document).ready(arguments[0]);
} else {
return {
ready: function(fn) {
console.log("registering function");
delayed_jquery.push(fn);
}
}
}
};
$ = jQuery;
var waitForLoad = function() {
if (typeof jQuery.fn != "undefined") {
console.log("jquery loaded!!!");
for (k in delayed_jquery) {
delayed_jquery[k]();
}
} else {
console.log("jquery not loaded..");
window.setTimeout(waitForLoad, 500);
}
};
window.setTimeout(waitForLoad, 500);
// end
// now lets use jQuery (the fake version)
jQuery(document).ready(function() {
alert('Jquery now exists!');
});
jQuery(function() {
alert('Jquery now exists, this is using an alternative call');
})
// And lets load the real jquery after 3 seconds..
window.setTimeout(function() {
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = true;
newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(newscript);
}, 3000);
&#13;