JS: parse dynamically added script before other scripts - javascript

I would like to have the following on my page:
a script ("script1.js") that adds a second script ("script2.js") dynamically to the page.
a third script ("script3.js").
"script3" overwrites some of the functions in "script2", therefore the order that the scripts should be parsed is:
script1 > script2 > script3.
And the console should show: 1 2 3. Instead I see 1 3 2.
I have tried using "defer" on "script3" with no success:
HTML file:
<html>
<head>
<script src="script1.js"></script>
<script defer type='text/javascript' src="script3.js"></script>
</head>
</html>
script1.js:
console.log('1');
var head = document.getElementsByTagName('head')[0];
const url = 'script2.js';
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
script2.js:
console.log('2');
script3.js:
console.log('3');

As ugly as it sounds, you could use document.write inside script1.js to load script2.js. The scripts will execute in correct order.
// script1.js
console.log('1');
document.write('<script src="script2.js"></script>');

Related

Loading sequence of scripts in html

I want to load a constants file as per the language the user has selected. For that I want to load the scripts dynamically.
<html>
<body>
<script type="text/javascript">
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
jsElement.src = "../constants.en.js";
document.body.appendChild(jsElement);
</script>
<script type="text/javascript" src="../js/RandomScript.js"></script>
</body>
Whole code is in HTML.
When I tried the code above, RandomScript.js is loaded before the constant file.
How can I maintain sequence of loading files.
I am not using jQuery or something, so is there any way to do interpolation of src of script?
You can use onload event listener to load .js files sequentially.
First create an array of URLs of scripts. Then loop through it recursively. onload event listener ensures that the scripts are loaded sequentially.
var scriptURLs = [
"../constants.en.js",
"../js/RandomScript.js"
];
function loadScript(index){
if(index >= scriptURLs.length){
return false;
}
var el = document.createElement('script');
el.onload = function(){
console.log("Script loaded: ", scriptURLs[index]);
loadScript(index+1);
}
el.src = scriptURLs[index];
document.body.appendChild(el);
// OR
// document.head.appendChild(el);
}
loadScript(0); // Load the first script manually.
Hope this helps.
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
document.body.appendChild(jsElement);
jsElement.onload = () => {
callyournewScript();
}
jsElement.src = "../constants.en.js";
Load the ../js/RandomScript.js after loading the ../constants.en.js like following
<body>
<script type="text/javascript">
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
jsElement.src = "../constants.en.js";
document.body.appendChild(jsElement);
var script = document.createElement("script");
script.src = "../js/RandomScript.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
</script>
<!-- <script type="text/javascript" src="../js/RandomScript.js"></script> -->
</body>

Error In Embed Script Into Page: 'Failed to execute 'write' '

I am just try inject JW player into the page but I keep getting the error:
14 Failed to execute 'write' on 'Document': It isn't possible to write
into a document from an asynchronously-loaded external script unless
it is explicitly opened.
My code is as follows:
<html>
<body>
<div id="jw-live"></div>
</body>
<script type="text/javascript">
var url = new URL(window.location);
var id = url.searchParams.get("id");
var script = document.createElement("script");
script.src = "https://content.jwplatform.com/players/"+ id +".js";
script.type = 'text/javascript';
script.async = true;
window.document.getElementById("jw-live").appendChild(script);
</script>
</html>
Am I doing something wrong?

JavaScript URL checking for pupunder

I have some javascript that checks the url is "musicmartian.com" and will then run a script that displays a pupunder ad, but doesnt seem to work.
the code is:
<script type="text/javascript">
if (window.location.href=="musicmartian.com") {
src='//go.oclaserver.com/apu.php?zoneid=540338'
}
</script>
The website is: http://musicmartian.com/ and the ad provider is PropellorAds if thats needed information.
Insert this code inside body of your html (before </body>)
<script type="text/javascript">
if (window.location.hostname === "musicmartian.com") {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//go.oclaserver.com/apu.php?zoneid=540338';
document.body.appendChild(script);
}
</script>

Javascript Append a new Jquery file with noconflict

I need to append a new version of jquery into head section as below.
<head>
<script type="text/javascript" async="" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">var $jq = jQuery.noConflict(true);</script>
<script>
$jq(document).ready(function() {
// works well
});
</script>
</head>
It works fine when I put it directly. But my case is, I need to append it dynamically, reslove noconflict and the implementation using external javascript file (my.js). (As below)
my.js file should be consisted with the all implementation.
// insert jquery file
var jqueryfile = document.createElement('script');
jqueryfile.type = 'text/javascript';
jqueryfile.async = true;
jqueryfile.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(jqueryfile, s);
How to do my implementation with jQuery.noConflict() and $jq(document).ready(function() {}).
Thank you!
You can try this to insert script in HEAD section
head1=document.getElementsByTagName("head")[0];
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
var s1 = document.createElement("script");
s1.type = "text/javascript";
s1.innerHTML="var $jq = jQuery.noConflict(true);
$jq(document).ready(function() {
// works well
});
";
head1.appendChild(s);
head1.appendChild(s1);
you only need to include a regular js file in the regular fashion like so and alias jQuery as a parameter, freeing up the dollar sign:
<script type="text/javascript">js/scripts.js</script>
and then add this to your scripts.js file:
;(function ( $ ) {
// all code in this anonymous function will not conflict with any other library
// and it will never get in to the global namespace which is good
$(document).ready(function() {
// works well
});
})( jQuery );
now you can just use the "$" for jQuery freely

Cross browser issue with script tag

I have the below code that will dynamically create the script tag.
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var variable1 = getUrlVars()["parameter1"];
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);
</script>
<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="window.location.href='https://www.google.com?'">
</body>
</html>
But somehow the above code doesn't work in IE but it works fine in Chrome. I am not sure what is the reason? Can anybody help me with that?
This whole things doesn't work in IE.
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);
You can dynamically add a script element using the following function.
var create_script = function(data) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = data;
//if you have to debug dynamically loaded script in chrome use the following - sourceURL has changed in the recent versions of chrome devetools.
//script.text = data + "\n\n //# sourceURL=" + ns + ".js\n";
//append the script element to body or head or where it seems fit.
document.body.appendChild(script);
}
the "data" parameter is the actual javascript code/URL that will form the part of the script tag. You are missing this in your code.
EDIT:
for non-standard attributes you might want to change the doctype according to http://www.w3schools.com/DTD/dtd_attributes.asp

Categories