There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request): http://jsfiddle.net/9N7Z2/188/
There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...
您可以使用一些现有的JavaScript加载程序,或者通过观察window.jQuery
来定义自己的JavaScript加载程序.
// Immediately-invoked function expression
(function() {
// Load the script
const script = document.createElement("script");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js';
script.type = 'text/javascript';
script.addEventListener('load', () => {
console.log(`jQuery ${$.fn.jquery} has been loaded successfully!`);
// use jQuery below
});
document.head.appendChild(script);
})();
请记住,如果您需要支持104个旧浏览器(如IE8),load
事件处理程序不会执行.在这种情况下,您需要使用重复的window.setTimeout
轮询window.jQuery
是否存在.这里有一个可以使用该方法的JSFdle:http://jsfiddle.net/9N7Z2/3/
有很多人已经做了你需要做的事情.查看一些现有的JavaScript加载程序框架,如: