如何在html元素中加载外部javascript函数?

时间:2019-11-16 09:30:25

标签: javascript html

我有一个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 个答案:

答案 0 :(得分:1)

我正试图弄清楚你的意思。据我推断,您希望将GenericService中的代码应用于具有特定特征的所有元素,而不是纯粹执行代码。

为此,您需要使用元素选择器之类的元素,例如

sample.js

更多信息可以在这里找到。

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

使用这些示例:

document.getElementByClassName(string);
document.getElementByTagName(string);
document.querySelectorAll(string);
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作为属性的任何元素的内容上。

请注意,此代码必须在末尾导入,以确保在脚本发生之前将所有元素添加到DOM并加载。

编辑1:

如这些评论中所述,请勿使用data-sample-js source

相反,我建议使用其他方法加载此内容。只需将document.write添加到页面顶部即可添加样式表,对于脚本,请使用动态加载器。有关<style>导入的更多信息,请参见here

编辑2:

您似乎正在尝试编写前端JavaScript代码以动态生成页面。您不应该这样做,而应该在为页面提供服务的后端应用程序中进行处理。在大多数后端语言/框架中,这相当简单(PHP可以简单地使用require_once)。

答案 1 :(得分: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';