简体   繁体   English

我通过动态添加脚本来加载iframe。 但是没有定义引用错误为$

[英]I have loading iframe by adding scripts dynamically. But getting a Reference error as $ is not defined

I'm calling the function after adding the jquery script. 我在添加jquery脚本后调用该函数。 but still, I'm getting a Reference error 但仍然出现参考错误

<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>

Due to JavaScript is executed asynchronously your Script cannot be loaded before JS tries to use the jQuery Object and therefor $ is not defined . 由于JavaScript是asynchronously执行的,因此在JS尝试使用jQuery对象之前,无法加载您的脚本,因此$ is not defined You need to use something like promises . 您需要使用诸如promises东西。

This link can help you: 该链接可以帮助您:

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

I thought this is not an issue. 我以为这不是问题。 this should be handle in sample level since you have append the external script directly without waiting to load it from cdn. 这应该在示例级别进行处理,因为您直接添加了外部脚本,而不必等待从CDN加载它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM