【问题标题】:I have loading iframe by adding scripts dynamically. But getting a Reference error as $ is not defined我通过动态添加脚本来加载 iframe。但是由于 $ 未定义而得到参考错误
【发布时间】:2019-02-27 22:49:06
【问题描述】:

我在添加 jquery 脚本后调用该函数。但是,我仍然收到参考错误

<script>
    window.onload = function(){
        AddScript("https://cdn.syncfusion.com/js/assets/external/jquery-1.11.3.min.js");

        $(function () { //Error throws while executing this line
            //My code here
        });
    }

    function AddScript(source)
   {
      var head= document.getElementsByTagName('head')[0];
      var script= document.createElement('script');
      script.src= source;
      head.appendChild(script);
   }
</script>

【问题讨论】:

标签: javascript iframe referenceerror dynamic-script-loading


【解决方案1】:

由于 JavaScript 被执行asynchronously,您的脚本在 JS 尝试使用 jQuery 对象之前无法加载,因此$ is not defined。你需要使用promises之类的东西。

此链接可以帮助您:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

【讨论】:

    【解决方案2】:

    我认为这不是问题。这应该在示例级别处理,因为您已经直接附加外部脚本而无需等待从 cdn 加载它。

    https://humanwhocodes.com/blog/2009/07/28/the-best-way-to-load-external-javascript/

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 2015-01-01
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      相关资源
      最近更新 更多