简体   繁体   中英

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. 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 . You need to use something like promises .

This link can help you:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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