dimanche 12 juin 2016

How to run script after jQuery.getScript is called?


I have a use case where I am checking if code is on the page, if it is not I use $.getScript to fetch the script. In the done I am trying to call a function that is in that script but it gives an error Uncaught ReferenceError: listInit is not defined. I have also set an interval to check for the function, but it is not finding it. What would be a good way to call the function that is in the external I am calling in? Here is the get script call, and my function that is in my external:

Get Script:

jQuery.getScript(scriptUrl)
      .done(function() {
        listInit(listOptions);
      });

Function in external that is called in:

var listInit = function(options) {
    console.log(options)
}

I can see in the network tab the call and the response shows my minified code. I have also tried this to see if the function is available:

jQuery(document).ready(function(){
  var findListFunction = setInterval(function(){
    if (typeof listInit !== 'undefined' && $.isFunction(listInit)) {
      console.log('Its available')
    }else{
      console.log('no such function')
    }
  },1000);
});

EDIT:

I put a console log in the external file outside of the function. The console log is executed once the external is called in. I just cant seem to get the function to run.


Aucun commentaire:

Enregistrer un commentaire