Fire onload event when script is loaded

So I have the following code:

 $.proxy(function(responseData) {
                    if (responseData.hasOwnProperty('dynamicJavascriptUrl')) {
                         var script = document.createElement('script');
                        script.src = responseData.dynamicJavascriptUrl;
                        script.load = function() {
                            console.log('hello');
                        }
                        $('#credit_card').append($(script));
                    }

And what I am trying to do here is to log hello when the script is loaded. But it doesnt seem to work.

I have tried this as well:

 script.onload = function() {
                            console.log('hello');
                        }

But with the same result.

Does anyone have an idea what to do?

Upvotes: 0

Views: 103

Answers (1)

Shiyam Kumar U
Shiyam Kumar U

Reputation: 52

Try This Code

jQuery.loadScript = function (url, callback) {
   jQuery.ajax({
      url: url,
      dataType: 'script',
      success: callback,
      async: true
   });
}

$.loadScript('dynamicJavascriptUrl.js', function(){
    console.log('hello');
});

Upvotes: 2

Related Questions