Search code examples
javascriptsynchronousdynamic-loading

Load a script dynamically within the <head> element


Okay so I'm trying to load a backup .js file synchronously in the event of a script dependency being unavailable, and everything seems to be working fine except for the fact that said script doesn't actually load, even though the element itself with the src is created:

[etc]

<head>
<script id = 'self'>
 if (typeof jQuery === 'undefined') {

  function insertAfter(referenceNode, el) { 
    referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling); 
  }

  var loadjq = document.createElement('script');

  // backup CDN
  loadjq.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js'; 

  loadjq.type = 'text/javascript';
  // loadjq.async = false;

  insertAfter(document.getElementById('self'), loadjq);

 }  
</script>

// element IS created here: <script src = 'https://ajax.google...' type = 'text/...'></script>
// but nothing is executed

<script>
  console.log($); // Reference Error
</script>
</head>

[etc]

Do note that I have not put this within a DOMContentLoaded event or anything, but I feel this should be working. I tested with Chrome and Firefox, and it's not a caching error. Any suggestions?


Solution

  • Note, this isn't ideal, however if you absolutely need to you can use the following.

    Use document.write to achieve this synchronously.

    <script>
    document.write(`jQuery is: ${typeof(jQuery)}.`);
    </script>
    
    <script>
    document.write(`<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"><\/script>`);
    </script>
    
    <script>
    document.write(`jQuery is: ${typeof(jQuery)}.`);
    </script>

    Note that you cannot have </script> in the string directly as this will terminate the actual script tag.