javascript tag in innerhtml - javascript

Like the title says I'm trying to add a javascript tag into a innerHTML.
I have a combobox and depending on which value is selected it should load a script into a div
the script looks like this:
<script type="text/javascript">
_cashieProductID=292016;
document.write(unescape("%3Cscript src='" +
('https:' == document.location.protocol ? 'https://' : 'http://') +
"somelink.js'
type='text/javascript'%3E%3C/script%3E"));
</script>
when I put this into my script it shows all kind of text on my page that is part of the combobox script. So I hope someone can help me how to insert this code into my script so it will show the content that gets loaded with the code given above.

HTML
<select id="product" onchange="validate()">
function validate()
{
pName = document.getElementById('product');
var value = pName.options[pName.selectedIndex].value;
if(value == "4OFC")
loadJs(detail,"myjsSrc");
else if(/*some conditon*/)
{
// use this ladder to change the script address based on value of select box
}
else{
}
}
function loadJs(targetDiv,source)
{
var ele = document.getElementById(targetDiv);
if(ele)
{
var scr = document.createElement('script');
scr.type = 'text/javascript';
scr.src = source;
ele.appendChild(scr);
}
}

Just try the actual string in document.write, like this:
document.write("<script src='" + ('https:' == document.location.protocol ? 'https://' : 'http://') + "somelink.js' type='text/javascript'></script>");

Related

Looking for an alternative to document.write for gpt.js file declaration

What can I use in place of document.write in JavaScript? Is there a different way to rewrite this line of code?
document.write('<scr' + 'ipt src="' + src + '"></scr' + 'ipt>');
Assuming your document.write statement was already in an executing script tag, you could substitute it with:
var script = document.createElement('script')
script.src = src
var first = document.getElementsByTagName('script')[0]
first.parentNode.insertBefore(script, first)
Demo:
// a delayed check to see if the script loaded
setTimeout(function() {
console.log(window.jQuery ? 'jQuery loaded!' : 'Uh oh!')
}, 5000)
<script>
var script = document.createElement('script')
// example src
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
var first = document.getElementsByTagName('script')[0]
first.parentNode.insertBefore(script, first)
</script>

Load Javascript file with Javascript based on URL

Can I use Javascript to load a Javascript file in HTML based on a string in URL?
For example something like this:
<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1)
{
include ('javascript_deutch.js)
}
else
{
include ('javascript_english.js)
}
</script>
I cannot use any other method like PHP or something.
Thanks for the help guys.
Unfortunately none of these things seem to work.
This
<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1) {
document.head.innerHTML+='<script src="javascript_deutch.js"></script>';
}else{
document.head.innerHTML+='<script src="javascript_english.js"></script>';
}
</script>
ended up just displaying a message at the top of my page:
'; }else{ document.head.innerHTML+=''; }
And this
<script type="text/javascript">
var script = document.createElement('script');
if (location.path.indexOf("DEUTCH") > -1) {
script.src = 'javascript_deutch.js';
} else {
script.src = 'javascript_english.js';
}
document.body.appendChild(script);
</script>
did not request the files on the server at all.
Am I missing something?
You can create a <script> tag dynamically:
var script = document.createElement('script');
if (location.path.indexOf("DEUTCH") > -1) {
script.src = 'javascript_deutch.js';
} else {
script.src = 'javascript_english.js';
}
document.body.appendChild(script);
The easy way without framework:
var _script = document.createElement('script');
_script.src = 'fileName.js';
document.body.appendChild(_script);
May be will be good to isolate this into separate function like this:
function includeJsFile(fileName) {
var _script = document.createElement('script');
_script.src = fileName;
document.body.appendChild(_script);
}
But may be will be good for you to check
http://requirejs.org/
Why not. Just add them in the script tags.
<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1) {
document.head.innerHTML+='<script src="javascript_deutch.js"></script>';
}else{
document.head.innerHTML+='<<script src="javascript_english.js"></script>';
}
</script>
Try this code, this method worked for me:
<script>
document.write('<script type="text/javascript" src="' + language-file + '.js"><\/script>')
</script>

Duplicate injection references

I'm developing some functionality that puts some adds on the my clients page.
I just give them some javascript that they have to add to their page.
That javascript as an identifier to the id of the add (for constructing purpose).
The javascript for every add is like this:
var _adds = _adds || [];
_adds.push(['ID_OF_THE_ADD_XXXXX']);
(function() {
var script = document.createElement('script');
script.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.myswebsite.com/myjs.js';
script.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(script);
})();
So, the hard part is that myjs.js is added many times to the head of client's page.
I already tried to declare some variable com myjs.js and check that var here but without success because everything is async.
Is there a way to not duplicate this?
Thanks in advance.
okay just got that before loading the prev script it is getting executed again so try this.
var _adds = _adds || [];
_adds.push(['ID_OF_THE_ADD_XXXXX']);
(function() {
if(typeof window.checker ==='undefined'){
window.checker = true;
var script = document.createElement('script');
script.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.myswebsite.com/myjs.js';
script.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(script);
}
})();

Script not getting loaded in order

I have been building script tag using javascript.when I use this script to load the three other scripts,the script is not loading in order.I want jquery.min.js to get loaded first. So I have used that as the first parameter. But it is not getting loaded at first. so I have been caught up with reference error. Can anyone tell me what mistake I have done in this code. My code is here
<script type="text/javascript">
(function (a, b, c) {
var g = document.createElement('script');
g.type = 'text/javascript';
g.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://') + a;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(g, s);
var g = document.createElement('script');
g.type = 'text/javascript';
g.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + b;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(g, s);
var g = document.createElement('script');
g.type = 'text/javascript';
g.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + c;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(g, s);
})('ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', '.example.com/js/script.js', '.example.com/js/form.js');
</script>
Use require.js for dynamic script loading.It will work.Also, try to use jquery.js above the website rather generate using script.
After my studing around this toppics, I updated for who visit to this question later.
For most of the browsers (IE9, Firefox, Chrome, Safari, ...) except Opera (12.16), dynamic script injection into DOM will load script asynchronously.
So this code:
function loadScript(src) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
}
loadScript('script1.js');
loadScript('script2.js');
loadScript('script3.js');
is almost equivalent to:
<script src="script1.js" async></script>
<script src="script2.js" async></script>
<script src="script3.js" async></script>
But if the async flag is set to false explicitly like:
function loadScript(src) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.async = false;
}
then the scripts will be loaded in order synchronously.
So the very short answer for this question is that g.async = false, but still I also recommend to use some framework and that is the best answer.
Try this: http://jsfiddle.net/DRCzN/
~~~~ original answer ~~~~~~
Dynamic script insertion (createElement('script') then insertBefore() or even insertAfter()) will load each script asynchronously.
So with your current script, the arrival of those script to the browser heavily depends on the network status.
If you want keep the dependency of these scripts, you can use some script loader such as $script, head.js or Require.js.
EDIT: I like Jonathan's solution, and here is a little improvement using $.getScript().
if script.js and form.js are independent of each other
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function(scripts) {
var protocol = ('https:' == document.location.protocol ? 'https://ssl.' : 'http://www.');
$.each(scripts, function(i, s) {
$.getScript(protocol + s);
});
})(['.example.com/js/script.js', '.example.com/js/form.js']);
</script>
if form.js depneds on script.js
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function(scripts) {
var protocol = ('https:' == document.location.protocol ? 'https://ssl.' : 'http://www.');
$.getScript(protocol + scripts[0], function() {
$.getScript(protocol + scripts[1]);
});
})(['.example.com/js/script.js', '.example.com/js/form.js']);
</script>
It's close, but use insertAfter, and remember to increase the index for each script.
var s = document.getElementsByTagName('script')[0];
g.parentNode.insertBefore(s, g.nextSibling);
...
var s = document.getElementsByTagName('script')[1];
g.parentNode.insertBefore(s, g.nextSibling);
...
var s = document.getElementsByTagName('script')[2];
g.parentNode.insertBefore(s, g.nextSibling);
Here's another example. This one uses an array of scripts to add, reverses them and then inserts after the current script tag.
EDIT: Can you get away with loading jQuery directly, as below. Using // a the start will make the resource load under the current protocol.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function (scripts) {
var protocol = ('https:' == document.location.protocol ? 'https://ssl.' : 'http://www.'),
thisScript = document.getElementsByTagName('script')[0];
function createScriptTag(element, index, array) {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = protocol + element;
thisScript.parentNode.insertBefore(newScript, thisScript.nextSibling);
};
(scripts || []).reverse().forEach(createScriptTag);
})(['example.com/js/script.js', 'example.com/js/form.js']);
</script>
Here is another method of solving this problem :
<script type="text/javascript">
window.onload = function () {
"use strict";
function js(n) {
var s = document.createElement('script');
s.setAttribute("type", "text/javascript");
s.setAttribute("src", n);
document.getElementsByTagName("head")[0].appendChild(s);
}
js("http://requirejs.org/docs/release/2.1.8/minified/require.js");
js("http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
js("http://www.example.com/form.js");
js("http://www.example.com/script.js");
};
</script>
This can also be used rather than the code explained in question.

simple solution to run third party javascript-tags in paralell? ("asyncronously")?

is there any simple solution to run third party javascript-tags in paralell?
just a few scripts on a html page, which shall not load one after another/sequencial
i know for advertisments it works useing an adserver like doubleclick but that is not necessary here and its not only ads
some need to stay able to analyse the html content the user-agent, ip, referrer or more
examples, that you may very well know :
1.
<script src="http://another-ad-service.com/get-js.aspx?&cwadformat=728*90"</script>
2.
<script language="JavaScript" type="text/javascript">
var 1a_account = '12345';
var 1a_zonesize = '12345-5';
var 1a_adtype = 'js';
</script>
<script type="text/javascript" src="http://agency1a.somewhere/12345.js"></script>
3.
<script type='text/javascript'>
<!--//<![CDATA[
document.MAX_ct0 ='';
var m3_u = (location.protocol=='https:'?'https://an-advertisment-agency.honolulu...'
var m3_r = Math.floor(Math.random()*99999999999);
document.write ("<scr"+"ipt type='text/javascript' src='"+m3_u);
document.write ("zoneid=12345");document.write("&nodis=1");
document.write ('&cb=' + m3_r);
if (document.MAX_used != ',') document.write ("&exclude=" + document.MAX_used);
document.write (document.charset ? '&charset='+document.charset :
(document.characterSet ? '&charset='+document.characterSet : ''));
document.write ("&loc=" + escape(window.location));
if (document.referrer) document.write ("&referer=" + escape(document.referrer));
if (document.context) document.write ("&context=" + escape(document.context));
if ((typeof(document.MAX_ct0) != 'undefined') &&
(document.MAX_ct0.substring(0,4) == 'http')) {
document.write ("&ct0=" + escape(document.MAX_ct0));
}
if (document.mmm_fo) document.write ("&mmm_fo=1");
document.write ("'></scr"+"ipt>");
//]]>--></script>
4.
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-12345-2']);
_gaq.push(['_setDomainName', 'website.edu']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ?
'https://ssl' : 'http://www') + '.gooooogle-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript"> window.google_analytics_uacct = "UA-12345-2"; </script>
When load external JavaScript files, you can add the async attribute to your script tag.
<script src="http://another-ad-service.com/get-js.aspx?&cwadformat=728*90" async></script>
The script needs to be self-sufficient and not depend on other code you are loading before that script, though.

Categories