Ali*_*aly 8 html javascript jquery twitter-bootstrap
我在加载Bootstrap库时遇到错误,因为它总是会出现此错误:
未捕获的错误:Bootstrap的JavaScript需要jQuery
尽管我Bootstrap确保jQuery加载但仍然得到错误后我附加了库.
我正在使用以下代码jQuery通过创建元素将其附加到页面并将其附加到document:
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '3.1.1') {
console.log("jQuery LOADED");
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js");
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
console.log(window.jQuery.fn.jquery);
scriptLoadHandler();
}
};
} else {
console.log("ONLOAD STATE");
script_tag.onload = scriptLoadHandler;
}
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
Run Code Online (Sandbox Code Playgroud)
在这里,我正在创建Bootstrap后document准备:
function main() {
jQuery(document).ready(function ($) {
var bootstrap_script = document.createElement('script');
bootstrap_script.setAttribute("type", "text/javascript");
bootstrap_script.setAttribute("src",
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(bootstrap_script);
})
}
Run Code Online (Sandbox Code Playgroud)
只是为了澄清一个关键的事情,我js在一个单独的js文件中编写代码,因为我想稍后使用jQuery plugin.因此,我正在尝试附加库,因为我不保证目标页面是否包含这些库
尝试使用 https 加载 jquery
script_tag.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js");
Run Code Online (Sandbox Code Playgroud)
希望它能起作用。