这就是我所拥有的:
<script src="myscript.js" type="text/javascript"></script>
<script type="text/javascript">testfunction("hello");</script>
在 myscript.js 中:
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.src = 'jquery-1.9.0.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
}
function testfunction(str) {
$(document).ready(function () {
alert(str);
});
}
当然,当前的 testfunction 不需要 jQuery,但它会是必需的。使用这种方法,当调用 testfunction() ( Uncaught ReferenceError: $ is not defined )时,jQuery 被下载但没有加载到浏览器中。
我可以做的是在加载我的 JS 之前在不同的脚本中加载 jQuery。在这种情况下,它会起作用,但我会拥有三个不同的脚本,老实说,这似乎并不优雅。
有没有其他方法可以实现这一目标?
谢谢!