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

166 views Asked by At

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

There are 2 answers

0
M K On BEST ANSWER

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/

0
messerbill On

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