情况
在我帮助维护的 Web 应用程序中,指定了一项更改,其中必须根据页面上是否存在某个元素 ID 有条件地加载某个 JavaScript 脚本。
问题
如何在没有外部库的情况下以符合当前公认实践的方式最好地实现这一结果?
当前的方法想法
我目前的想法是做类似以下的事情;我希望得到一些指导,包括回复:这种方法是否可取和/或更好的替代方法。
// identify head of html
const htmlHead = document.querySelector('head');
// identify desired change condition and assign
const desiredIdPresent = document.querySelector('#foo');
// assign script creation
const activeScript = document.createElement('script');
activeScript.type = 'text/javascript';
// conditions determine which script loads
if (desiredIdPresent){
activeScript.src = '/foo.js';
} else {
activeScript.src = '/bar.js';
};
// insert desired script into document head
htmlHead.appendChild(activeScript);
下面有一些有些类似的情况和解决方案,其中我也作为引用:
最佳答案
该问题是由于页面加载的同步方面造成的。
您的代码似乎在加载之前尝试搜索 #foo
。
解决方案:将脚本标签放在正文的末尾。 示例:
<body>
<div id="foo"></div>
<script>
// identify head of html
const htmlHead = document.querySelector('head');
// identify desired change condition and assign
const desiredIdPresent = document.querySelector('#foo');
console.log(desiredIdPresent);
// assign script creation
const activeScript = document.createElement('script');
activeScript.type = 'text/javascript';
// conditions determine which script loads
if (desiredIdPresent){
activeScript.src = '/foo.js';
} else {
activeScript.src = '/bar.js';
};
// insert desired script into document head
htmlHead.appendChild(activeScript);
</script>
<!-- OR --> <script src="k.js"/>
</body>
我没有碰过你的JS一厘米。
关于javascript - 如何根据页面 HTML 文件中特定 ID 标记的存在有条件地加载 JavaScript 资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59846953/