Waiting for dynamically loaded script

Aaron Digulla picture Aaron Digulla · Sep 5, 2011 · Viewed 100.6k times · Source

In my page body, I need to insert this code as the result of an AJAX call:

    <p>Loading jQuery</p>
    <script type='text/javascript' src='scripts/jquery/core/jquery-1.4.4.js'></script>
    <p>Using jQuery</p>
    <script type='text/javascript'>
        $.ajax({
            ...
        });
    </script>

I can't use $.load() since the document has already loaded, so the event doesn't fire.

Is this safe? If not, how do I make sure the jquery script has loaded before my custom, generated code is executed.

Answer

Rob Fox picture Rob Fox · Mar 28, 2017

Add an ID to your script file so you can query it.

<script id="hljs" async src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.0.0/highlight.min.js"></script>

Then add a load listener to it in JavaScript

<script>
  var script = document.querySelector('#hljs');
  script.addEventListener('load', function() {
    hljs.initHighlightingOnLoad(); 
  });
</script>