简体   繁体   中英

How to add a script tag to the head section after a specific script tag

I am using a single page application. I am trying to add a <script></script> tag to the head from my nested div in the page after specific javascript code, but I got the error below. Please find my jsp code below.

How to add a script tag after a specific script tag in the head tag from a nested div?

TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

<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>

appendChild accepts the parameter of type node or HTML element - https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild and you are passing the string . Instead create element using document.createElement .

const script = document.createElement('script');
script.textContent = `window.dataLayer = window.dataLayer || []; dataLayer.push('<%=gtm%>')`;

document.getElementsByTagName('head')[0].appendChild(script);

To insert the script after specific script tag, you can add custom attribute and then select that element and use insertAdjacentElement to insert new created script after it.

// 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);

use document.getElementById("some").insertAdjacentElement('afterend',script); and add it next to the script tag using 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM