如何在HTML元素中加载外部JavaScript函数?

3
我有一个名为sample.js的文件,其中包含:
document.write('<script>........</script><a>...</a><style>....</style>');

在外部网站中,我有这个脚本 <script src="https://example.com/sample.js"></script>。无论在哪里使用此脚本,sample.js 都会立即加载。即使我使用了 document.write,所有其他元素也不会被删除。
我想在多个 Html <div> 或其他元素中加载上述脚本,其中我们定义类似于 id="example"class="example"data-sample-js 的内容。
那么我该如何修改 sample.js 文件以实现这一点?
到目前为止,我已经尝试在 sample.js 中:
window.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll("[data-sample-js]").forEach(elem => {
 elem.innerHTML = document.write('<script>...</script><a>...</a><style>...</style>');
});});

无论我们在哪里放置 <script src="https://example.com/sample.js"></script> 以及 <div data-sample-js></div>,JavaScript 都会被加载,但它会删除页面中的所有其他 HTML 元素。
编辑:
There is a full html document is placed in the document.write(). 
It can have multiple scripts, styles, metas and all other possible codes.
that will be present in a static html webpage, including <script src="...">
2个回答

1

我正在努力理解您的意思。从我的推断来看,您希望将sample.js中的代码应用于具有特定特征的所有元素,而不仅仅是执行代码。

为此,您需要使用诸如元素选择器之类的工具。

document.getElementByClassName(string);
document.getElementByTagName(string);
document.querySelectorAll(string);

更多内容可以在这里找到。

https://plainjs.com/javascript/selecting/

使用它们的一个示例:

document.querySelectorAll("[data-sample-js]").forEach(elem => {
    elem.innerText += "This is a sample text";
});
<div data-sample-js>Test</div>

这个代码将会把This is a sample text连接到具有data-sample-js属性的任何元素内容中。

请注意,为了确保所有元素都被添加到DOM并在脚本执行之前加载完毕,此代码必须放在末尾导入。

编辑1:

如评论中所提到的,请不要使用document.writesource

相反,我建议使用其他方法来加载此内容。可以通过将<style>添加到页面头部来添加样式表,对于脚本,则使用动态加载器。关于<script>导入的更多信息可以在here找到。

编辑2:

看起来你正在尝试编写前端JavaScript代码以动态生成页面。你不应该这样做,而是应该在后端应用程序中处理它,以便为页面提供服务。在大多数后端语言/框架中,这非常简单(PHP可以简单地使用require_once)。


这个很好用。但是有没有一种方法,让它在脚本放置在页面的任何位置时都能工作? - lisdoa
脚本可以在任何地方导入,但请确保它被包装在 onload 中,以确保在执行操作之前页面已完全加载。 - Hive7
我只是在问,是否可以将js文件添加到顶部而不是底部。由于我使用document.write,当我使用window.addEventListener('DOMContentLoaded')时,所有HTML代码已经存在于页面上将被删除。 - lisdoa
我使用了 document.write,因为它包含 scriptstyle 元素。 - lisdoa
脚本和样式元素可以动态创建,无需使用document.write。查看此链接以了解有关脚本的更多信息:https://dev59.com/cnA75IYBdhLWcg3wg5fs,您可以使用`document.createElement`来创建样式(或者只需使用`document.head.innerHTML += ...`添加样式)。 - Hive7
显示剩余2条评论

0

也许this就是您想要实现的内容。

简而言之:

var scriptTag = document.getElementsByTagName('script');
scriptTag = scriptTag[scriptTag.length - 1];
var parentTag = scriptTag.parentNode;
parentTag.innerHTML = 'This is a sample text to replace its content';
parentTag.classList.add('new_class');
parentTag.id = 'new_id';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接