我使用以下命令将jQuery库附加到dom:
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
Run Code Online (Sandbox Code Playgroud)
但是,当我跑:
jQuery(document).ready(function(){...
Run Code Online (Sandbox Code Playgroud)
控制台报告错误:
Uncaught ReferenceError: jQuery is not defined
Run Code Online (Sandbox Code Playgroud)
如何动态加载jQuery以及在dom中使用它?
我一直在使用这个函数将onload处理程序附加到脚本标记,它似乎是互联网上推荐的方式.
然而,如果页面已经加载(在8中测试),它在Internet Explorer中不起作用.您可以看到它在普通浏览器中有效(加载脚本时会触发警报).
我错过了什么吗?
谢谢
我正在为自己编写一个JavaScript工具,我计划向其他人提供它并使用jQuery.我对这个小实用程序的梦想是让人们能够.js从远程源中包含一个文件,并且在加载该文件时,让它检查是否已经包含jQuery,如果有,则确保它是一个最近的版本,以便与我的代码需要做的兼容.一些伪代码可以更清楚地解释我的问题(这段代码会出现在.js我之前提到的单个文件的顶部):
if jQuery is loaded {
if version is less than (say) 1.3 {
// load latest version of jQuery
}
} else {
// load latest version of jQuery
}
// and do the jQuery.noConflict()
// dance to avoid trampling any other libraries, etc. that the
// user may be utilizing.
// The rest of my code lives here, happy in the knowledge that it's running in
// isolation from the rest of the JS …Run Code Online (Sandbox Code Playgroud)