Saravana Kumar
Saravana Kumar

Reputation: 394

Jquery script is not loaded, on appendChild

I am loading my script files dynamically using this code,

<script type="text/javascript">
  var newscript = document.createElement('script');
  newscript.type = 'text/javascript';
  newscript.src = '../static/js/jquery.js';
  document.getElementsByClassName('container')[0].appendChild(newscript);

  var newscript = document.createElement('script');
  newscript.type = 'text/javascript';
  newscript.src = '../static/js/report_app.js';
  document.getElementsByClassName('container')[0].appendChild(newscript);

</script>

It throws error as,

Reference error: $ is not defined 

in report_app.js.

I thought, jquery.js script must be loaded into the DOM when the next file, report_app.js is being parsed.

But the error shows, jquery.js is not executed. How to ensure one script file is loaded before running the next one?

Upvotes: 4

Views: 529

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

It is because the script is added asynchronously, you can use the onload callback

function addScript(path, callback) {
    var newscript = document.createElement('script');
    newscript.type = 'text/javascript';
    newscript.src = path;
    newscript.onload = callback;
    document.body.appendChild(newscript);

}

addScript('http://code.jquery.com/jquery-1.11.2.js', function () {
    addScript('../static/js/report_app.js');
})

Demo: Fiddle

Upvotes: 5

Related Questions