JavaScript IF/ELSE to call another JS Script? - javascript

I need to call one of two JavaScripts depending on a condition, like so:
<script type="text/javascript">
if(b_condition)
<script type="text/javascript" src="http://script1.js"></script>
else
<script type="text/javascript" src="http://script2.js"></script>
</script>
But this doesnt work. Any ideas how to call another JavaScript call in an If/Else block?

What the hell? Why on earth is everyone here advocating document.write()? Fairly certain we've moved beyond this as standard practice by this point; document.write isn't even valid if you're in an XHTML setting.
The best way to do this would be something like the following (also here, for better highlighting/parsing: https://gist.github.com/767131):
/* Since script loading is dynamic/async, we take
a callback function with our loadScript call
that executes once the script is done downloading/parsing
on the page.
*/
var loadScript = function(src, callbackfn) {
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.setAttribute("async", "true");
newScript.setAttribute("src", src);
if(newScript.readyState) {
newScript.onreadystatechange = function() {
if(/loaded|complete/.test(newScript.readyState)) callbackfn();
}
} else {
newScript.addEventListener("load", callbackfn, false);
}
document.documentElement.firstChild.appendChild(newScript);
}
if(a) {
loadScript("lulz.js", function() { ... });
} else {
loadScript("other_lulz.js", function() { ... });
}
If you have jQuery or a similar library on the page, you can jack out my loadScript function and insert their appropriate function (ala $.getScript, etc).

You could do something like this:
var file=document.createElement('script')
file.setAttribute("type","text/javascript")
file.setAttribute("src", "script1.js")
Forgot to add that you need to then append this into an element on the page:
document.getElementsByTagName("head")[0].appendChild(file)

I used this and it works well:
<script type="text/javascript">
if(b_condition)
document.write('<scri'+'pt src="http://script1.js"></'+'script>');
else
document.write('<scri'+'pt src="http://scripts2.js"></'+'script>');
</script>
I see that document.write is not the best practice to use though, but it works. Any ideas better than this? I don't want to write so much code for something so simple.

<script type="text/javascript">
if(condition==true)
{
var src = "js/testing_true.js";
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.setAttribute("async", "true");
newScript.setAttribute("src", src);
document.body.appendChild(newScript);
}else
{
var src = "js/testing_false.js";
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.setAttribute("async", "true");
newScript.setAttribute("src", src);
document.body.appendChild(newScript);
}
</script>

If the scripts are not huge and/or there is no other reason why not both should be loaded, I would do something like:
<script type="text/javascript" src="http://script1+2.js"></script>
<script type="text/javascript">
if(b_condition) {
functionA();
}
else {
functionB();
}
</script>

You need to either emit the desired script block in your condition, or create the script tag using the DOM and insert it. http://ajaxpatterns.org/On-Demand_Javascript

Those files script1.js and script2.js are your, or are u including them from another domain?
because if they are yours your can include both, and depends of your condition you can call functions inside the files..

This is usually a bad idea so I recommend that you tell us what you actually need to do so we can find a better solution for you. In general you would like to combine and minify all javascript needed on the page so the user only has to load it once.
If there is no other way than you can do it like this:
<script type="text/javascript">
var script = document.createElement('script');
if((b_condition){
script.src = 'script1.js';
}else{
script.src = 'script1.js';
}
document.body.appendChild(script);
</script>

<script type="text/javascript">
if(b_condition)
document.write('<script type="text/javascript" src="http://script1.js"></script>');
else
document.write('<script type="text/javascript" src="http://script2.js"></script>');
</script>

<?php if (a_condition) {?>
put html code here or script or whatever you like
<?php } elseif(b_condition) {?>
put any other code here
<?php } else {?>
put even more code
<?php } ?>

Related

How do I reference code in dynamically added js files?

I try to add js files dynamically.
I found several guides for that and in Page inspector, they all seem like they work…
However, I cannot reference any code in the newly added files.
My three code examples that look like they work fine... but don't.
//v1
var th = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', scriptName);
th.appendChild(s);
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);
//v2
var s = document.createElement('script');
s.setAttribute('src', scriptName);
document.head.appendChild(s);
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);
//v3
let myScript = document.createElement("script");
myScript.setAttribute("src", scriptName);
document.head.appendChild(myScript);
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);
do i have to append the scripts differently or is my reference call wrong / not possible?
the Guides that exactly explain my requirement seem somehow not to work for me ?!
https://www.kirupa.com/html5/loading_script_files_dynamically.htm
Dynamically adding js to asp.net file
Thanks in advance for any help
The three methods to add a script element are essentially the same*.
As dynamically added script elements do not load the resources synchronously, you need to listen to the load event on the global object. DOMContentLoaded is another idea, but it fires too soon as it does not wait for resources to have loaded.
Here is a demo with loading jQuery asynchronously. The output shows the type of the jQuery variable, which will be "function" once that resource is loaded:
let scriptName = "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.js";
// v3
let myScript = document.createElement("script");
myScript.setAttribute("src", scriptName);
document.head.appendChild(myScript);
console.log("Synchronous, jQuery =", typeof jQuery);
document.addEventListener("DOMContentLoaded", function () {
console.log("After DOMContentLoaded event, jQuery =", typeof jQuery);
});
window.addEventListener("load", function () {
console.log("After load event, jQuery =", typeof jQuery);
});
* The first version also defines the type attribute, but the HTML5 specification urges authors to omit the attribute rather than provide a redundant MIME type.
Consider this working example:
// dyn.js
window.zzz = 1;
<!--index.html-->
<html>
<head>
<script>
function includeJs(url)
{
if (!url) throw "Invalid argument url";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
}
includeJs("dyn.js");
function documentLoaded()
{
alert(window.zzz)
}
</script>
</head>
<body onload="javascript:documentLoaded()">
</body>
</html>
An obvious difference between your code and this is that the sample above loads the script during the document loading and the usage of the script code happens after the document has finished loading.
If you need to do a late-loading of a dynamic script depending on some run-time parameters, here are some options:
If you have control over the dynamically-loading script, you could add a function in your loader script and call it at the last line of the dynamically-loading script:
// dyn.js
window.zzz = 1;
if(typeof(dynamicLoadingFinished) != "undefined") dynamicLoadingFinished();
<!--index.html-->
<html>
<head>
<script>
function includeJs(url)
{
if (!url) throw "Invalid argument url";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
}
function documentLoaded()
{
includeJs("dyn.js");
window.dynamicLoadingFinished = function()
{
alert(window.zzz)
}
}
</script>
</head>
<body onload="javascript:documentLoaded()">
</body>
</html>
Another possible approach would be to use the good old XMLHttpRequest. It will allow you yo either force synchronous loading (which is not advisable because it will block all JavaScript and interactivity during loading, but in certain situations can be of use):
// dyn.js
window.zzz = 1;
<!--index.html-->
<html>
<head>
<script>
function includeJs(url)
{
if (!url) throw "Invalid argument url";
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send();
var script = document.createElement("script");
script.text = request.responseText;
document.head.appendChild(script);
}
function documentLoaded()
{
includeJs("dyn.js");
alert(window.zzz)
}
</script>
</head>
<body onload="javascript:documentLoaded()">
</body>
</html>
or load the script asynchronously and wait for the request to finish:
// dyn.js
window.zzz = 1;
<!--index.html-->
<html>
<head>
<script>
function includeJs(url, finished)
{
if (!url) throw "Invalid argument url";
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function ()
{
if (request.readyState == 4 || request.readyState == 0)
{
if (request.status == "200")
{
var script = document.createElement("script");
script.text = request.responseText;
document.head.appendChild(script);
return finished();
}
else throw request.responseText;
}
};
request.send();
}
function documentLoaded()
{
includeJs("dyn.js", () => alert(window.zzz));
}
</script>
</head>
<body onload="javascript:documentLoaded()">
</body>
</html>
I believe the AJAX samples could be written also with the more modern fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).

onload event is not firing

I've implemented this answer in order to solve my problem but I still can't get the onload event fire.
I need a javascript solution, and I'm trying this on chrome. I know that I need to check for readystate for IE.
What am I missing here?
<script>
var script = document.createElement('script');
script.type = "type/javascript";
document.getElementsByTagName('head')[0].appendChild(script);
script.onload = function(){
console.info("After loading");
mdp.video.loadAllPlayers(".videoPlaceholder");
};
script.src = "/source.min.js";
</script>
Something like that
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="application/javascript">
var el = document.createElement('script');
el.src = "//cdnjs.cloudflare.com/ajax/libs/less.js/1.3.3/less.min.js"; // use what ever js file you want but valid one
el.onload = function(script) {
console.log(script + ' loaded!');
};
document.body.append(el);
</script>
</body>
</html>

priority of the executed javascript

Say I use google map api via two sites
<head>
<script
src="https://maps.googleapis.com/maps/api/js?sensor=false&hl=zh-CN&v=3.21&callback=initMap" async defer>
</script>
<script
src="http://ditu.google.cn/maps/api/js?sensor=false&hl=zh-CN&v=3.21&callback=initMap" async defer>
</script>
</head>
<body>
<script>
function initMap() {
//something
}
</script>
</body>
Sometimes I can't connect to the first site, but the code still works. Now I want to use the first site whenever I can connect to it. Is there a way to set the priority of the two sites?
You could load the first with javascript using document.createElement and add an onerror event handler that sets the src to the second source if the first fails:
<script>
var script = document.createElement('script');
script.src = 'http://ditu.google.cn/maps/api/js?sensor=false&hl=zh-CN&v=3.21&callback=initMap';
script.onerror = function() {
// if the above source fails to load, try this one
this.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&hl=zh-CN&v=3.21&callback=initMap';
this.onerror = function() {
console.log('Nothing loaded!');
}
}
script.async = true;
script.defer = true;
document.body.appendChild(script);
</script>

Appending Jquery in HTML dynamically

I am new to jquery. I am trying to append Jquery in an HTML page in java. To include jquery.js file I have written following code:
scriptTag += "var script = document.createElement('script');" +
"script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'; " +
"script.type = 'text/javascript'; " +
"document.getElementsByTagName('head')[0].appendChild(script);" +
and then I appended following js+jquery code with it
"var script2 = document.createElement('script'); window.onload = function() {" +
"$(document).ready(function() {" +
"$(\"#identity\").hide();});};" +
"script2.type = 'text/javascript'; " +
"document.getElementsByTagName('head')[0].appendChild(script2);";
So basically I am trying to write this :
var script = document.createElement('script');
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var script2 = document.createElement('script');
window.onload = function() {
$(document).ready(function() {
$("#identity").hide();
});
};
script2.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script2);
What I want to do is that I want my function after window load. Somehow, writing $(document).ready(function() { alone does'nt work. I get an error that $ is not defined (looks like jquery.js is not ready yet).
To avoid this problem I have used window.onload = function() {. But now I am getting error: $(document).ready is not a function. I am really confused here on how to write this thing. Is this the correct approach? Any help/guidance is highly appreciated.
[Edit]
Please note that the following code (without jquery) works fine:
window.onload = function() {
document.getElementById('identity').style.visibility='hidden';
};
[Edit]
Actually I am making a web proxy, where I download page and serve them with custom look and field. The pages does not contain any jquery files nor can I include or write HTML. I can only add my Js dynamically using java etc.
Here is some code that shows how to load a script file dynamically and also delay calling of $(document).ready until that file is loaded:
http://jqfaq.com/how-to-load-java-script-files-dynamically/
The code you use to load jquery.min.js file is called asycnhroniously. Probably this file has not been loaded at the moment you try to execute jquery function.
Therefore you should make sure that the file is loaded using a callback function.
In the following link you can find an example on how to this:
http://blog.logiclabz.com/javascript/dynamically-loading-javascript-file-with-callback-event-handlers.aspx
Also here is a working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>index</title>
<script type="text/javascript">
function loadScript(sScriptSrc, callbackfunction) {
//gets document head element
var oHead = document.getElementsByTagName('head')[0];
if (oHead) {
//creates a new script tag
var oScript = document.createElement('script');
//adds src and type attribute to script tag
oScript.setAttribute('src', sScriptSrc);
oScript.setAttribute('type', 'text/javascript');
//calling a function after the js is loaded (IE)
var loadFunction = function() {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
callbackfunction();
}
};
oScript.onreadystatechange = loadFunction;
//calling a function after the js is loaded (Firefox)
oScript.onload = callbackfunction;
//append the script tag to document head element
oHead.appendChild(oScript);
}
}
var SuccessCallback = function() {
$("#identity").hide();
}
window.onload = function() {
loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', SuccessCallback)
};
</script>
</head>
<body>
<span id="identity"> This text will be hidden after SuccessCallback </span>
</body>
You should use this code in your scriptTag variable and then you can use eval() function to evaluate the script in this variable. Also you can load the second javascript file in the callback function using jquery's getscript function

how can i load <script>'s into an iframe?

I've got the logic working to append into my iframe from the parent
this works:
$('#iframe').load(function() {
$(this).contents().find('#target').append('this text has been inserted into the iframe by jquery');
});
this doesn't
$('#iframe').load(function() {
$(this).contents().find('body').append('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>');
});
.lf
The problem is something to do with the inserted script tags not being escaped properly.
Half of the javascript is becomes visible in the html, like the first script tag has been abruptly ended.
Maybe the error is with your string, never create a string in javascript with a literal < /script> in it.
$('#iframe').load(function() {
$(this).contents().find('body').append('<scr' + 'ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></scr' + 'ipt>');
});
I'm a bit surprised that isn't working [Edit: No longer surprised at all, see mtrovo's answer.]...but here's what I do, which is mostly non-jQuery per your comment below but still quite brief:
var rawframe = document.getElementById('theframe');
var framedoc = rawframe.contentDocument;
if (!framedoc && rawframe.contentWindow) {
framedoc = rawframe.contentWindow.document;
}
var script = doc.createElement('script');
script.type = "text/javascript";
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js";
framedoc.body.appendChild(script);
Off-topic: I really wouldn't give an iframe (or anything else) the ID "iframe". That just feels like it's asking for trouble (IE has namespace issues, and while I'm not aware of it confusing tag names and IDs, I wouldn't be completely shocked). I've used "theframe" above instead.
Warning: loading script in this manner would make scripts running in main window context
i.e.: if you use window from somescript.js, it would be NOT iframe's window!
$('#iframe').load(function() {
$(this).contents().find('body').append('<scr' + 'ipt type="text/javascript" src="somescript.js"></scr' + 'ipt>');
});
To be able to use iframe context inject script with this:
function insertScript(doc, target, src, callback) {
var s = doc.createElement("script");
s.type = "text/javascript";
if(callback) {
if (s.readyState){ //IE
s.onreadystatechange = function(){
if (s.readyState == "loaded" ||
s.readyState == "complete"){
s.onreadystatechange = null;
callback();
}
};
} else { //Others
s.onload = function(){
callback();
};
}
}
s.src = src;
target.appendChild(s);
}
var elFrame = document.getElementById('#iframe');
$(elFrame).load(function(){
var context = this.contentDocument;
var frameHead = context.getElementsByTagName('head').item(0);
insertScript(context, frameHead, '/js/somescript.js');
}

Categories

Resources