如果未加载,请加载jQuery - 失败的方法 [英] Loading jQuery if not loaded - failed approach

查看:91
本文介绍了如果未加载,请加载jQuery - 失败的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在:

 < script src =myscript.jstype =text / javascript >< /脚本> 
< script type =text / javascript> testfunction(hello);< / script>

内部myscript.js:

<$ p $如果(!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);

$ b $函数testfunction(str){
$(document).ready(function(){
alert(str);
});
}

当然,jQuery对于当前的测试功能并不需要,但它会被需要。使用这种方法,当调用testfunction()( Uncaught ReferenceError:$未定义)时,jQuery被下载但未加载到浏览器。

我能做的是在我的JS加载之前在另一个脚本中加载jQuery。在这种情况下,它会起作用,但我会有三种不同的脚本,而且我认为这看起来不够高雅。



是否有其他方法可以实现这一点?



谢谢!

解决方案

您可能想试试看此答案。它可能不会等到jQuery完全加载。


This is what I have in :

<script src="myscript.js" type="text/javascript"></script>
<script type="text/javascript">testfunction("hello");</script>

Inside 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);
    });
}

Of course jQuery is not needed for the current testfunction, but it will be needed. Using this approach, jQuery is downloaded but NOT loaded to the browser when calling to testfunction() (Uncaught ReferenceError: $ is not defined).

What I could do is to load jQuery in a different script before my JS is loaded. In that case, it will work, but I would have three different scripts and that seems to be not elegant in my honest opinion.

Is there any other way to achieve this?

Thanks!

解决方案

You might want to try looking at this answer. It may not be waiting until jQuery is fully loaded.

这篇关于如果未加载,请加载jQuery - 失败的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆