我正在使用单页应用程序。我正在尝试在特定的JavaScript代码之后从页面中的嵌套div的头部添加<script></script>
标记,但是出现以下错误。请在下面找到我的jsp代码。
如何在嵌套div的head标签中的特定脚本标签之后添加脚本标签?
TypeError:无法在“节点”上执行“ appendChild”:参数1为 不是“节点”类型
<html>
<head>
<!-- Google Tag Manager -->
<script>
(function(w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
'gtm.start' : new Date().getTime(),
event : 'gtm.js'
});
var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l='
+ l
: '';
j.async = true;
j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-5HWKRLC');
</script>
**<! Here i need to add another script when my inner div loading !>**
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
...
</head>
<body>
<% String gtm = (String) session.getAttribute("gtmObj"); %>
<div>
<script>
document.getElementsByTagName('head')[0].appendChild('<script>window.dataLayer = window.dataLayer || [];dataLayer.push(<%=gtm%>)<\/script>');
</script>
</div>
</body>
</html>
答案 0 :(得分:1)
appendChild
接受类型为node
或HTML element
-https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild的参数,并且您正在传递string
。而是使用document.createElement
创建元素。
const script = document.createElement('script');
script.textContent = `window.dataLayer = window.dataLayer || []; dataLayer.push('<%=gtm%>')`;
document.getElementsByTagName('head')[0].appendChild(script);
要在特定的script
标记后插入script
,可以添加自定义属性,然后选择该元素,然后使用insertAdjacentElement
在其后插入新创建的脚本。
// HTML
<script data-id = "myScript"></script>
// Javascript
const script = document.querySelector("script[data-id='myScript']");
const newScript = document.createElement('script');
newScript.textContent = "const a = 10";
script.insertAdjacentElement('afterend', newScript);
答案 1 :(得分:1)
使用document.getElementById("some").insertAdjacentElement('afterend',script);
,并使用insertAdjacentElement
将其添加到脚本标签旁边
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute('textContent', '<script>window.dataLayer = window.dataLayer || [];dataLayer.push(<%=gtm%>);dataLayer.push({\'event\':\'Txn\',\'Affiliation\':\'Vehicle\'})<\/script>');
document.getElementById("some").insertAdjacentElement('afterend',script);
<html>
<head>
<!-- Google Tag Manager -->
<script id="some">
(function(w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
'gtm.start' : new Date().getTime(),
event : 'gtm.js'
});
var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l='
+ l
: '';
j.async = true;
j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-5HWKRLC');
</script>
</head>
<body>
something
</body>
</html>