Home > Software engineering >  Include Javascript inside JS file
Include Javascript inside JS file

Time:01-02

How can we include javascript link inside .js file?. .js file support include, require or import like CSS or PHP?

My Code :

// Global site tag (gtag.js) - Google Analytics

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.googletagmanager.com/gtag/js?id=UA-51600743-15';
document.body.appendChild(script);

  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-51600743-15');


// Microsoft Clarity

    (function(c,l,a,r,i,t,y){
        c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
        t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/" i;
        y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
    })(window, document, "clarity", "script", "9zvbjor3bn");



//Start of Tawk.to Script

var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/61d019a4c82c976b71c45176/1foae8bkm';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();

I am trying to add all tracking code inside one file analytic.js and adding that to my website so it will be easy for me to maintain in future, so i do not need to edit in every page whenever any changes required in tracking codes.

What is the correct way to include another js file inside js file?

async src="https://www.googletagmanager.com/gtag/js?id=UA-51600743-15";
//OR
require("https://www.googletagmanager.com/gtag/js?id=UA-51600743-15"};
//OR
import from "https://www.googletagmanager.com/gtag/js?id=UA-51600743-15";
//Or any other way?

CodePudding user response:

Guide : https://www.geeksforgeeks.org/how-to-include-a-javascript-file-in-another-javascript-file/

Solution :

function include(file) {
  
  var script  = document.createElement('script');
  script.src  = file;
  script.type = 'text/javascript';
  script.defer = true;
  
  document.getElementsByTagName('head').item(0).appendChild(script);
  
}
  
/* Include Many js files */
include('https://example.com/example.js');

CodePudding user response:

You can include them like this,

 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'https://www.googletagmanager.com/gtag/js?id=UA-51600743-15';
 document.body.appendChild(script);
  • Related