I encountered the following script in a webpage source :
<script type="text/javascript">
WebFontConfig = {"typekit":{"id":"cmr1bul"}};
(function() {
var wf = document.createElement('script');
wf.src = 'https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
</script>
From what I see, this script inserts the content of https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js
before the first script in the page. What is the difference between the above and putting
<script type="text/javascript" src="https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js"> </script>
as the first script in the page ? What is gained by using the longer version ?
It's absolutely equivalent to the following code if both script elements are added before any other one:
<script>WebFontConfig = {"typekit":{"id":"cmr1bul"}};</script>
<script src="https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js" async></script>
...or:
<script src="https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js" async></script>
<script>WebFontConfig = {"typekit":{"id":"cmr1bul"}};</script>
...because the script is asynchronously included...
Related
I want to inject a matomo tag manager script into the head section of a page by javascript code. However when I try the code in matomo preview mode, the code doesn't fire. What am I misssing?
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = `
var _mtm = window._mtm = window._mtm || [];
_mtm.push({'mtm.startTime': (new Date().getTime()), 'event': 'mtm.Start'});
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.async=true; g.src='http://url.com/matomo/js/container_xyz.js'; s.parentNode.insertBefore(g,s);
`;
document.head.appendChild(script);
The problem was on the matomo side. Code works
I added a Cookies Consent banner. The requirement is that https://cdn.cookielaw.org/consent/c4337328/OtAutoBlock.js loaded before any other script. I now wonder if appendChild is the right choice. Will it load OtAutoBlock at the exact position I wrote it or will it append the script to the end of the tag (which would be too late). It has to be the first script that's loaded.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- OneTrust Cookies Consent Notice -->
<script type="text/javascript">
if ("%REACT_APP_COOKIE_BAR%" === "true") {
var otAutoBlock = document.createElement("script");
otAutoBlock.setAttribute("type", "text/javascript");
otAutoBlock.setAttribute("src", "https://cdn.cookielaw.org/consent/c4337328/OtAutoBlock.js");
var otSDKStub = document.createElement("script");
otSDKStub.setAttribute("type", "text/javascript");
otSDKStub.setAttribute("src", "https://cdn.cookielaw.org/scripttemplates/otSDKStub.js");
otSDKStub.setAttribute("charset", "UTF-8");
otSDKStub.setAttribute("data-domain-script", "c4337328");
document.getElementsByTagName("head")[0].appendChild(otAutoBlock);
document.getElementsByTagName("head")[0].appendChild(otSDKStub);
function OptanonWrapper() { }
}
</script>
<script type="text/javascript">
/* [Should load after OtAutoBlock loads to avoid tracking before consent was given] */
</script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
document.head.appendChild(script) will add it to the end of the <head> tag, so it will load after all other scripts. You can do two things:
You load it with appendChild at the end, and have all your other scripts with a defer attribute, like this: <script defer> /* something */ </script> The defer forces a script to execute after the page is loaded, but if you load the OtAutoBlock without a defer, it will run before the others. The only thing to note is that defer will cause the scripts not to run last, but after the entire page loads, which includes CSS stylesheets, other JavaScripts, icons, images, HTML content, XHR requests in <script> tags, etc.
<script>
const load = true; // your stuff here
if (load)
{
const script = document.createElement('script');
window.hasRunned = false;
script.text = 'alert(\'OtAutoBlock running.\'); window.hasRunned = true;';
document.head.appendChild(script);
}
</script>
<script defer>
alert('Another script. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
<script defer>
alert('And yet another. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
You use insertBefore to add it before the other scripts, so it will run before them. No need to use defer with this method. This might be what you want if you need the scripts to run before the page loads.
<script>
const load = true; // your stuff here
if (load)
{
let script = document.createElement('script');
window.hasRunned = false;
script.text = 'alert(\'OtAutoBlock running.\'); window.hasRunned = true;';
document.head.insertBefore(script, document.head.children[0]);
}
</script>
<script>
alert('Another script. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
<script>
alert('And yet another. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
With this HTML the function myFunc() can be executed. https://myurl.de/myjs.js has the function myFunc in it.
<head>
<script type="text/javascript" src="https://myurl.de/myjs.js"></script>
<body>
<script type="text/javascript">
myFunc();
</script>
</body>
</head>
But with the second HTML I get an Error: Uncaught ReferenceError: myFunc is not defined.
https://myurl.de/settingsFile.js is a file that includes this url in a var: https://myurl.de/myjs.js so basically SettingsFile.UrlToMyJS is this https://myurl.de/myjs.js
<head>
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript" id="myid"></script>
</head>
<body>
<script type="text/javascript">
document.getElementById('myid').src = SettingsFile.UrlToMyJS;
myFunc();
</script>
</body>
When I console.log(document.getElementById('myid')) this is the output:
<script type="text/javascript" id="myid" src="https://myurl.de/myjs.js></script> which is correct. It looks exactly like the script in the head of the first html (with the difference that it has the id="myid").
Yet it does not work. Why and how can I fix it?
settingsFile.js:
var defaultURL = 'https://myurl.de/';
var SettingsFile = {
UrlToMyJS : defaultURL + 'myjs.js',
}
The reason it's not working is that you can't add a src to a script element that's already in the DOM — or rather, doing so doesn't do anything. The script element has already been processed.
Instead, create it and then append it:
var script = document.createElement("script");
script.onload = function() {
myFunc();
};
script.src = SettingsFile.UrlToMyJS;
document.head.appendChild(script);
// If you need to support IE8, use the following instead of the previous line:
//document.getElementsByTagName("head")[0].appendChild(script);
That waits for the script to load, then calls myFunc (which should exist by then).
Also note that as I and Jeremy pointed out in the comments, body doesn't go in head, it goes after. It's also generally best to put script tags at the end of body (if you're not using async or defer attributes on them or type="module"). So in all, something like:
<head>
<!-- head stuff here -->
</head>
<body>
<!-- content here -->
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript">
var script = document.createElement("script");
script.onload = function() {
myFunc();
};
script.src = SettingsFile.UrlToMyJS;
document.head.appendChild(script);
// If you need to support IE8, use the following instead of the previous line:
//document.getElementsByTagName("head")[0].appendChild(script);
</script>
</body>
Another option is to use document.write. This sort of thing may be the last at-least-partially appropriate use of document.write during the main parsing of the page:
<head>
<!-- head stuff here -->
</head>
<body>
<!-- content here -->
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript">
document.write('<script src="' + SettingsFile.UrlToMyJS + '"><\/script>');
</script>
<script>
myFunc();
</script>
</body>
You can try creating a element and then appending it to your title
For Example (script code) :
var script = document.createElement("script");
script.src = "YOUR_SCRIPT_SRC_HERE";
document.getElementsByTagName('head')[0].appendChild(script);
Here I am creating a new tag in html and then appending it to the head of your html. Even as T.J. Crowder mentioned in the comment try removing your body from the head
I would like to know how to pass the value of a variable in JavaScript file to a variable in a script function which is written on top of the HTML file.
I wrote it like this:
myjsfile.js:
var abc = "10";
HTML file:
<html>
<head>
<script type="text/javascript">
(function() {
var test = document.createElement('script'); test.type = 'text/javascript'; test.async = true;
test.src = 'testquery.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(test, s);
alert(abc);
})();
</script>
</head>
<body>
</body>
</html>
I am not getting the output. Please help! Thanks in advance.
Basically I am trying to create a jquery plugin just like Google analytics.
The script has to load first, try using onload
test.onload=function(){alert(abc);}
<html>
<head>
<script type="text/javascript" src="testquery.js"></script>
<script type="text/javascript">
alert(abc);
</script>
</head>
<body></body>
</html>
try this:
(function() {
var test = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(test);
test.type = 'text/javascript';
test.src = 'testquery.js';
test.onload = function () {
alert(abc);
}
})();
well.. the onload has already been told but you should at least switch your way of appending it to the head.
I have this self-executing function:
<script type="text/javascript">
(function() {
var sc = document.createElement('script');
sc.src = 'http://blahblah.com/test.js';
sc.type = 'text/javascript';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(sc, s);
})();
</script>
All that is contained in test.js is:
document.write('ping!');
However, it hangs -- am I doing something incorrect?
I found a way to go around the document.write but now the only question is why does this not work.
var nc = document.createElement('div');
nc.appendChild(document.createTextNode('blah'));
var scr = document.getElementsByTagName('script')[0];
scr.parentNode.insertBefore(nc, scr);
I have no idea what you're trying to accomplish, but your code is valid as long as it's hosted on http://blahblah.com/.
Your browser won't let you execute remote code to manipulate the original page. It's not that dumb.