Home > Back-end >  How to include external script into <script>?
How to include external script into <script>?

Time:03-22

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>

CodePudding user response:

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