0

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>
  • You need to load scripts by asynchronously, refer the below link. [Asynchronous load](https://stackoverflow.com/questions/7718935/load-scripts-asynchronously) – Shanmugaraja_K Sep 24 '18 at 12:32

2 Answers2

0

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

messerbill
  • 5,499
  • 1
  • 27
  • 38
0

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/

M K
  • 1,821
  • 4
  • 11
  • 22