在< head>中动态加载脚本.元素 [英] Load a script dynamically within the <head> element

查看:82
本文介绍了在< head>中动态加载脚本.元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,因此,在脚本依赖项不可用的情况下,我试图同步加载备份.js文件 ,并且除了上述脚本没有即使创建具有src的元素本身,也不会真正加载:

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]

请注意,我没有将此事件置于DOMContentLoaded事件之内,但我认为这应该可行. 我使用Chrome和Firefox进行了测试,这不是缓存错误.有什么建议吗?

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?

推荐答案

注意,这不是理想的选择,但是,如果您绝对需要,可以使用以下内容.

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

使用document.write同步完成此操作.

<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>

请注意,您不能直接在字符串中包含</script>,因为这会终止实际的script标记.

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

这篇关于在&lt; head&gt;中动态加载脚本.元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆