在 <head> 元素中动态加载脚本
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
事件或其他任何内容中,但我认为这应该有效。
我用 Chrome 和 Firefox 测试过,这不是缓存错误。有什么建议吗?
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
标记。
好的,所以我正在尝试加载备份 .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
事件或其他任何内容中,但我认为这应该有效。
我用 Chrome 和 Firefox 测试过,这不是缓存错误。有什么建议吗?
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
标记。