'How to include external script into <script>?

Inside my JS function I need to add this:

< script src=https://xxxx.com/c3.js type="text/javascript" async defer>< /script>

How to edit the code the right way?

<script>
function affilate() {                   
        var ab_instance = "xxx.com";
        var ab_kampan = 3;
        var ab_cena = 1; 
        var ab_id_transakce = document.getElementById("email").value;
              
    <script src=https://xxxx.com/c3.js type="text/javascript" async defer></script>
                                    
    console.log(ab_id_transakce);
    }
 </script>


Solution 1:[1]

If I understand your question correctly, you are trying to add a script tag to the DOM. It seems that you are trying to add the HTML script tag in the Javascript function, which will not work. What you can try is:

  1. Add the script tag directly in the HTML like this:
<script src=https://xxxx.com/c3.js type="text/javascript" async defer></script>
<script>
function affilate() {                   
    var ab_instance = "xxx.com";
    var ab_kampan = 3;
    var ab_cena = 1; 
    var ab_id_transakce = document.getElementById("email").value;                             
    console.log(ab_id_transakce);
}
 </script>
  1. Add the script tag dynamically
<script>
    function affilate() {
        var ab_instance = "xxx.com";
        var ab_kampan = 3;
        var ab_cena = 1;
        var ab_id_transakce = document.getElementById("email").value;
        console.log(ab_id_transakce);

        var script_tag = document.createElement("script");
        script_tag.src = "https://xxxx.com/c3.js";
        script_tag.type = "text/javascript";
        script_tag.async = true;
        script_tag.defer = true;

        // in case you want to add the script tag to the <head>
        document.head.appendChild(script_tag);

        // in case you want to add the script tag to the <body>
        document.body.appendChild(script_tag);
    }
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robin Stut