![](/img/trans.png)
[英]How load script tag as DOM element and run as if it was placed in head tag
[英]Load a script dynamically within the <head> element
好的,因此,在脚本依赖项不可用的情况下,我试图同步加载备份.js
文件,并且除了该脚本实际上并未加载(即使元素本身带有src
被创建:
[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
事件或任何其他内容中,但是我认为这应该DOMContentLoaded
。 我使用Chrome和Firefox进行了测试,这不是缓存错误。 有什么建议么?
请注意,这并不理想,但是,如果您绝对需要,可以使用以下内容。
使用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
标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.