Load a script dynamically within the <head> element

橙三吉。 提交于 2019-12-02 22:34:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/57914397/load-a-script-dynamically-within-the-head-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!