Include Javascript inside JS file - javascript

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?

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

Related

Check is external Javascript has changed or not

Here is my code which might not be the best solution of my problem, and my goal is to check the external script (script.js) every 2 seconds if it's code has changed. If it is changed, then execute it.
function connectLoader(retval) {
console.log('Executing...');
var old = document.getElementById("EPMagic");
if (old !== null) {
old.outerHTML = "";
delete old;
}
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.setAttribute('id','EPMagic');
script.setAttribute('type','text/javascript');
script.setAttribute('src','http://server.com/script.js');
head.appendChild(script);
}
setInterval('connectLoader()',2000);
The problem is that /script.js is still executed even if it is not being changed.
The code on /script.js is simply alert('Execute');
Use setAttribue to set the attributes values:
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.setAttribute('id','loadScript');
script.setAttribute('type','text/javascript');
script.setAttribute('src','http://server.ip/script.js');
head.appendChild(script);

Where should analytics script be put in a React app?

Barion Pixel requires to put in code in my React app. When I put it in App.js or index.js, it raise an error. Do you have any idea where to put it? In index.html inhas no effect. Strange.
https://docs.barion.com/Implementing_the_Base_Barion_Pixel
<script>
// Create BP element on the window
window["bp"] = window["bp"] || function () {
(window["bp"].q = window["bp"].q || []).push(arguments);
};
window["bp"].l = 1 * new Date();
// Insert a script tag on the top of the head to load bp.js
scriptElement = document.createElement("script");
firstScript = document.getElementsByTagName("script")[0];
scriptElement.async = true;
scriptElement.src = 'https://pixel.barion.com/bp.js';
firstScript.parentNode.insertBefore(scriptElement, firstScript);
// Send init event
bp('init', 'addBarionPixelId', 'BP-0000000000-00');
</script>
I just show how error looks like:
You can try using dangerouslySetInnerHTML:
<script
dangerouslySetInnerHTML={{
__html: `
// Create BP element on the window
window["bp"] = window["bp"] || function () {
(window["bp"].q = window["bp"].q || []).push(arguments);
};
window["bp"].l = 1 * new Date();
// Insert a script tag on the top of the head to load bp.js
scriptElement = document.createElement("script");
firstScript = document.getElementsByTagName("script")[0];
scriptElement.async = true;
scriptElement.src = 'https://pixel.barion.com/bp.js';
firstScript.parentNode.insertBefore(scriptElement, firstScript);
// Send init event
bp('init', 'addBarionPixelId', 'BP-0000000000-00');`
}}
/>

Uncaught Error: Leaflet must be loaded before the leaflet heatmap plugin

I want to create a heatmap using heatmapjs and leaflet. However, I am stuck at loading the Javascript files. The error in my console says about 1 out of 2 times:
leaflet-heatmap.js:23 Uncaught Error: Leaflet must be loaded before the leaflet heatmap plugin
at leaflet-heatmap.js:23
at leaflet-heatmap.js:28
So half of the time it does load correctly, but the other half not.
I tried using different options suggested in different threads, none worked.
<script src="<?=base_url()?>leaflet/leaflet-src.js"></script>
<script type="text/javascript">
var myScript = document.createElement('script');
myScript.setAttribute('src', '<?=base_url()?>assets/js/plugins/heatmap.js');
document.head.appendChild(myScript);
myScript.onload = function() {
var script = document.createElement('script');
script.src = "<?=base_url()?>assets/js/plugins/leaflet-heatmap.js";
script.async = true;
document.head.appendChild(script);
};
</script>
or
<script async src="<?=base_url()?>assets/js/plugins/heatmap.js"></script>
<script src="<?=base_url()?>leaflet/leaflet-src.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(event) {
var script = document.createElement('script');
script.src = "<?=base_url()?>assets/js/plugins/leaflet-heatmap.js";
script.async = true;
document.head.appendChild(script);
});
</script>
or
<script async src="<?=base_url()?>assets/js/plugins/heatmap.js"></script>
<script src="<?=base_url()?>leaflet/leaflet-src.js"></script>
<script async src="<?=base_url()?>assets/js/plugins/leaflet-heatmap.js"></script>
Your script tags need to be loaded in a specific order. leaflet.js needs to be loaded first. If you use the async attribute on script tags, there is no guarantee in which order they are loaded. To fix your problem, omit the async attribute:
<script src="<?=base_url()?>assets/js/plugins/heatmap.js"></script>
<script src="<?=base_url()?>leaflet/leaflet-src.js"></script>
<script src="<?=base_url()?>assets/js/plugins/leaflet-heatmap.js"></script>

How do I add a javascript alert to innerHTML at runtime

When a particular event happens that I listen out for - I want to populate the div 'divDynamicAdvert` with the javascript that calls my Google Ad code.
Huge thanks to "tenbits" for showing me that I need to be appending a script node like this:
function myEventHandler(evt) //called when event is caught
{
var script = document.createElement('script');
script.textContent = 'alert(1)';
document.getElementById('divDynamicAdvert').appendChild(script);
}
This works great, but in place of the alert, I need to insert the Google Ads Javascript:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-3286208413631803";
/* Standard MPU */
google_ad_slot = "8630273973";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
I've tried:
var script = document.createElement('script');
script.textContent = 'google_ad_client = 'ca-pub-3286208413631803'; google_ad_slot = '8630273973'; google_ad_width = 300; google_ad_height = 250;';
document.getElementById('divDynamicAdvert').appendChild(script);
var script = document.createElement('script src="http://pagead2.googlesyndication.com/pagead/show_ads.js"');
document.getElementById('divDynamicAdvert').appendChild(script);
I've tried escaping the slashes too, but no luck... Can you guys help?
As #slebetman already said, innerHTML wont work. If you trying to evaluate script via DOM, and not eval(code), etc - do this with SCRIPT Node:
var script = document.createElement('script');
script.textContent = 'alert(1)';
document.getElementById('divDynamicAdvert').appendChild(script);
// actually it doesnt matter where you append it
EDIT:
In any case create a SCRIPT NODE, and then manipulate with it - add a script content to it OR add src attribute if you reference external source
var script;
// content
script = document.createElement('script')
script.textContent = 'alert(1)'
document.body.appendChild(script);
// google api source
script = document.createElement('script');
script.src = 'ANY_URL';
// -> in this case, same as script.setAttribute('src', 'ANY_URL');
document.body.appendChild(script);
Having some further questions, do not hesitate to ask in comments.

Multiple jQ.src in Bookmarklet

This is my current bookmarklet code.
if (1 == 1) {
var jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.onload=runthis;
jQ.src = 'http://www.domain.com/jquery-1.5.2.min.js';
document.head.appendChild(jQ);
}
I want to call multiple jQ.src. I tried this however it doesn't work on some sites.
This is my current bookmarklet code.
if (1 == 1) {
var jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.onload=runthis;
jQ.src = 'http://www.domain.com/jquery.js';
jQ.src = 'http://www.domain.com/jquery2.js';
document.head.appendChild(jQ);
}
On some sites it works and other it doesn't Any insight?
Thanks!
Are you sure that works on some sites? I think you're just getting lucky and picking up the site's already loaded jQuery.
Anyway, if you want to add two JavaScript files then you'll have to append two script tags:
var jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.src = 'http://www.domain.com/jquery.js';
document.head.appendChild(jQ);
jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.src = 'http://www.domain.com/jquery2.js';
jQ.onload = runthis;
document.head.appendChild(jQ);
Also note that the onload is only on the second one since you presumably need both JavaScript files loaded before runthis will work.
If you're loading jQuery, you might want to check if the page has loaded it already:
var jQ;
if(typeof window.jQuery != 'function') {
// jQuery isn't there yet so load it up.
jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.src = 'http://www.domain.com/jquery.js';
document.head.appendChild(jQ);
}
jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.src = 'http://www.domain.com/jQuery2.js';
jQ.onload = runthis;
document.head.appendChild(jQ);
Adding a jQuery.noConflict() call might be a good idea too, the page might be using $ for something else so forcing it to be jQuery could break the page.

Categories

Resources