我需要添加jquery,然后依赖于jquery的另一个脚本。 然后我需要使用这两个资产的代码,但我的问题是,我不希望我的代码运行,直到我知道两个资产都加载。等待脚本加载已通过javascript添加
我认为这个过程是加载jquery,然后等待,直到jquery通过等待window.onload加载,然后加载jquery插件,然后检测插件已经加载,然后加载我自己的代码,使用函数从jquery插件。
到目前为止的代码:
// load jquery if it is not allready loaded and put it into no conflict mode so the $ is available for other librarys that might be allready on the page.
if(!window.jQuery) {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
jQuery.noConflict(); // stop jquery eating the $
console.log("added jquery");
}
window.onload = function(e) {
// we know that jquery should be available now as the window has loaded
if (!jQuery.isFunction(jQuery.fn.serializeObject)) { // use jquery to ask if the plugins function is allready on the page (don't do this if the website already had the plugin)
// website didn't have the plugin so add it to the page.
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery-serialize-object/2.5.0/jquery.serialize-object.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
if (!jQuery.isFunction(jQuery.fn.serializeObject)) {
// console.log("serializeObject is undefined");
// its going to be undefined here because Its still loading in the script
} else {
// console.log("we have serializeObject");
}
// I now dont know when to call my code that uses .serializeObject() because it could still be loading
// my code
var form_data_object = jQuery('form#mc-embedded-subscribe-form').serializeObject();
};
如果jQuery的加载:[getScript加入(https://api.jquery.com/jquery。 getscript /) – Artem
@ user2129021请检查我的答案。 –