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.
Related
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');
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);
I am trying to load script and link using javascript.Previously I was using jquery not I am removing jquery from our project only using javascript.
previously I write like this
$('head link[data-reqjq][rel=preload]').each(function(){
var a = document.createElement('script');
a.async=false;
a.src=$(this).attr('href');
this.parentNode.insertBefore(a, this);
});
$(function(){
$('script[data-reqjq][data-src]').each(function(){
this.async=true;
this.src=$(this).data('src');
});
});
Now I am trying to load both things using javascript.
like this but it is not loading
var elements = document.querySelectorAll('head link[data-reqjq][rel=preload]');
Array.prototype.forEach.call(elements, function(el, i){
var a = document.createElement('script');
a.async=false;
a.src=this.getAttribute('href');
this.parentNode.insertBefore(a, this);
});
var elements = document.querySelectorAll('script[data-reqjq][data-src]');
Array.prototype.forEach.call(elements, function(el, i){
el.async=true;
el.src=el.data('src');
});
here is my code
https://jsbin.com/havuxujixi/3/edit?html,js,output
Simple Solution
/*
add JS File
*/
function addJsFileFunc(filename) {
document.getElementsByTagName('head')[0].innerHTML.toString().includes(filename + ".js"))
loadScript('/',filename + ".js");
}
addJsFileFunc("paht/script-file-name.js")
/*
script tag
*/
let scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.src = 'url.js';
document.getElementsByTagName('head')[0].appendChild(scriptTag);
1 - add a end tag to the script; </script> instead of /> (check here)
2 - your second query selector have an error in its callback : .data('src') should be .getAttribute('src')
also as a suggestion use simple forEach instead of Array.prototype.call
var elements = document.querySelectorAll('script[data-reqjq][data-src]');
elements.forEach(function(el, i){
el.async=true;
el.src=el.getAttribute('src');
});
the first selector can be written as:
var elements = document.querySelectorAll('head link[data-reqjq][rel=preload]');
elements.forEach(function(el, i){
var a = document.createElement('script');
a.async=false;
a.src=el.getAttribute('href');
// mounting new one inplace
el.parentNode.append(a);
// unmouting the old one
el.remove();
});
I need to append the css and js file dynamically and am using below method
document.getElementsByTagName('head')[0].appendChild();
this method doesn't allow second parameter.
I have to append both the css and js file dynamically. I am calling the above method twice to append the files. Any other generic way to restrict the above method to be called only once.
Here it is what i have tried:
var jscss = function(cp, sp){
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", cp);
document.getElementsByTagName('head')[0].appendChild(css);
var script = document.createElement('script');
script.src = sp;
document.getElementsByTagName('head')[0].appendChild(script);
};
jscss();
Well, I think you can achieve it by providing id to the element and before appending it just check if that element exists.
Example:
var jscss = function(cp, sp){
if(!document.getElementById("customStyleSheet")){
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("id", "customStyleSheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", cp);
document.getElementsByTagName('head')[0].appendChild(css);
}
if(!document.getElementById("customScript")){
var script = document.createElement('script');
script.src = sp;
script.id = "customScript";
document.getElementsByTagName('head')[0].appendChild(script);
}
};
jscss();
Hope this will help you :)
You could use a documentfragment in order to only need to call to appendChild once to add both elements:
var jscss = function(cp, sp){
var fragment = document.createDocumentFragment();
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", cp);
fragment.appendChild(css);
//Does not affect the DOM
var script = document.createElement('script');
script.src = sp;
fragment.appendChild(script);
//Does not affect the DOM
document.getElementsByTagName('head')[0].appendChild(fragment);
//Adds both elements to the DOM
};
jscss();
Use a variable to remember if the function has run already.
var jscss_run = false;
function jscss(cp, sp) {
if (jscss_run) {
return; // don't run a second time
}
jscss_run = true;
// do all the real work
}
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.