我对将 JS 文件动态加载到 DOM 中需要什么感到有些困惑。
当我包含在我的 HTML 文件中时,example.js 将正常运行。
当我包含它时,它会添加到 DOM 但不会运行它。
我以前认为我必须重新创建,然后将其 append() 到标签。我感觉好像我错过了关键的一步,我只是不知道那一步是什么。
示例.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="example.js"></script><!-- working -->
<script src="add-example-dynamically.js"></script><!-- not working -->
</head>
<body>
<script>
execute( anyScriptElement ); // not working
</script>
</body>
</html>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
add-example-dynamically.js
function toExecutable( tagElement ){
// Duplicate the provided tag as a new element in order for all tags to run the 'src' attribute after adding it to the DOM
// Required to run: <script src=""></script>
var newTag = document.createElement( tagElement.tagName );
if( tagElement.hasAttributes() ){
// Check if the tag has attributes
for( var countAttributes = 0; countAttributes < tagElement.attributes.length; ++countAttributes ){
var name = tagElement.attributes[ countAttributes ].name;
var value = tagElement.attributes[ countAttributes ].value;
newTag.setAttribute( name, value );
}
}
if( tagElement.textContent ){
// Check if the tag has content within it
newTag.textContent = tagElement.textContent;
}
return newTag;
}
function execute( anyScriptElement ){
var tag = toExecutable( anyScriptElement );
document.getElementsByTagName( 'head' )[ 0 ].append( tag );
}
var theScript = document.createElement( 'script' );
theScript.src = 'example.js';
execute( theScript ); // not working
Run Code Online (Sandbox Code Playgroud)
我尝试过的事情(或其中的变种)
我也一直在向各种对象添加.onload和.onreadystatechange,但没有成功。
我还不太明白的事情
如何在 HTML 索引文件中导入多个 javascript 文件而不会出现膨胀?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://humanwhocodes.com/blog/2009/07/28/the-best-way-to-load-external-javascript/
我认为不能解决我的问题的事情
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
https://gomakethings.com/a-better-way-to-load-scripts-with-javascript-or-why-document-write-sucks/
想法
我有一种感觉,正确的解决方案不涉及 XMLHttpRequest 或 Promises,但我不确定。
我有问题的存储库:小部件
如果有人能指出我正确的方向,那将帮助我弄清楚我需要研究什么。
供参考
Native JS 理想,对 JQuery 不感兴趣。
我只关心对 Chrome、Firefox、Opera、Safari(桌面/移动)的支持
所以我发现问题出在我解析代码的顺序上。我花了很长时间才找到,因为我的代码本质上没有任何问题,但顺序是错误的。
我以正确的顺序调用所有内容,但在我的网络面板中解决问题的顺序不正确。
一旦我修复了将事物加载到 DOM 中的顺序,一切就按预期进行了。
修复#1
因为我的 XMLHttpReqest 应该是异步的,所以我将所有调用放入一个 Javascript 文件中,以便它们同步运行。
在加载引用这些文件的函数调用之前,我需要将 Javascript 文件加载到标记中。
该函数调用我包裹在window.onload = function(){}.
基本上我的最终解决方案是对于<script>code</script>我动态放置在example.html中的任何内容,我将包装在window.onload = function(){}.
IE<script>window.onload = function(){ code }</script>
修复#2
window.onload = function(){}我在一个没有意义的位置使用了 onload 包装器。此外,它可能在调试时一度嵌套在另一个 window.onload 函数中,这可能没有帮助。
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |