How to include an external javascript file conditionally? [duplicate] - javascript

This question already has answers here:
Dynamically load a JavaScript file
(30 answers)
Closed 8 years ago.
I have this code:
<script src="http://external/js/file/url.js">
</script>
I want to do something like this-
<script>
if(2>1){
//include http://external/js/file/url.js
}
</script>
Any idea?

This question has been asked before in Include a Javascript File in another Javascript File.
This peice of code may fit what you have been looking for
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
if that script does not work, i suggest you to look over and read the post above: Include a Javascript File in another Javascript File.
I hope this helps, it may not be the answer you had been looking for, but it may just help.

You simply load it asynchronously like
if(yourCondition==true){
var d = document,
h = d.getElementsByTagName('head')[0],
s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://external/js/file/url.js';
h.appendChild(s);
}

You could use something like:
<script type="text/javascript">
if (condition == true) {
document.getElementsByTagName("head")[0].innerHTML += ("<script src=\"http://external/js/file/url.js\" type=\"text/javascript\"></script>");
}
</script>

Related

Loading a javascript dynamically in angular

I have got the following scenario and problem to solve. Any help will be appreciated.
Scenario
I have an angular application which calls a service(web api) and gets the contents back. The content is added to the html div. The content is as follow:
<script type="text/javascript" src="https://xxxx.com/ws/js/xxxxloader.js" id="theLoader"></script>
<script type="text/javascript">
// The code here look at the if the above script has been loaded properly by //checking the state of above script tag
</script>
I am adding the returned content to the HTML of the component in NgOnInit() as follow.
ngOnInit(){
this.apiService.getContent().subscribe(
d => {
this.responseString = d.toString();
var frag = document.createRange().createContextualFragment(this.responseString);
document.getElementById("theContainer").appendChild(frag);
}
);
}
However, it is failing because the first script tag (#theLoader) has never been loaded properly. I think it is because I am injecting the script tag after Dom has finished loading.
If you can see the better way of injecting the script, can you enlighten me.
Thanks in advance.
You can dynamically inject the JS URL by creating dynamic script tag
ngOnInit(){
function loadScripts(url: string){
var el = document.createElement('script');
el.onload = function(script){
console.log(script + ' loaded!');
// you can call the JS Function
};
el.src = url;
document.getElementsByTagName('body')[0].append(el);
}
</script>
ngAfterViewInit () {
this.loadScript('path to your js');
}
loadScript(url) {
console.log('preparing to load...')
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
}
Try this one :
ngOnInit(){
this.addScripts("https://xxxx.com/ws/js/xxxxloader.js", 'text/javascript');
this.addScripts("https://xxxx.com/js/mail.js", 'text/javascript');
}
addScripts(src, type): void{
var script = document.createElement('script');
script.src = src;
script.type = type;
document.querySelector('body').appendChild(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>

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

How do I add dynamic javascript to the head tag from a string, not a file?

I am using Javascript to generate additional custom javascript and then adding it to the HEAD tag. The code below works great adding a javascript file, but what if the script is in a variable just generated?
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", "myfile.js");
document.getElementsByTagName("head")[0].appendChild(scriptTag);
Thank you for your attention.
// script text
var txt = "alert('foo');";
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
// append it in a text node
scriptTag.appendChild(document.createTextNode(txt));
document.getElementsByTagName("head")[0].appendChild(scriptTag);
FWIW, you don't need a script tag for this. You can use the Function constructor instead.
var txt = "alert('foo');";
Function(txt)();
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.innerHTML = "What you want here";///....
document.getElementsByTagName("head")[0].appendChild(scriptTag);
Live DEMO
Both answers seem ok specially the one from #gdoron.
I've written a simple example in case you want to do the same thing in jquery: http://jsfiddle.net/bitoiu/EKpGg/
Snippet:
$(function(){
var script = document.createElement( 'script' );
script.type = 'text/javascript';
// script.url = 'some valid url';
$('head').append( script );
});​

Call Chrome.extension.sendRequest from a dynamically inserted js?

I'm currently trying to insert dynamically a JS block on a webpage using jQuery but it didn't work. I tried this :
var body = $('body');
var injectJs = $('<script type=text/javascript>' +
'$(document).click(function() {' +
'dropMenu("dropMenu1", 0);' +
'});');
body.append(injectJs);
EDIT : 16:26
I've succeed to insert the code by this way :
/* Importation de Tool.js */
var scriptImport = document.createElement('script');
scriptImport.type = 'text/javascript';
scriptImport.src= chrome.extension.getURL('js/Tool.js');
head.appendChild(scriptImport);
/* Injection du script onClick */
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = "document.addEventListener('click', function(){ dropMenu('slideUp', 0); alert('TRY ME AGAIN'); });";
And dropMenu :
function dropMenu(dropMenuPage, marginLeft)
{
var msg = "";
msg = msg.concat(dropMenuPage, "|", marginLeft);
chrome.extension.sendRequest({dropMenu : msg});
alert('After send');
}
The problem is that the sendRequest is impossible from this page... Someone have an idea ?
Thanks in advance.
You need a closing </script> at the end there...
I think its just your script stag isn't closed
var b= $('body');
var injectJs = $('<script type=text/javascript> $(document).click(function() {alert("yes");});</script>');
b.append(injectJs);
Use eval function, such as eg:
var body = $('body');
var injectJs = eval("$(document).click(function() {alert('hello')})");
body.append(injectJs);
Why not use content scripts for this? Injecting script directly to the page is only required if you need to access js variables from the page. For your dropMenu() a content script should be enough.
You cannot use Chrome API inside injected js. You would need to also inject a content script, and using custom DOM events you would be able to communicate with it from your injected script. Then this content script would be able to call Chrome API and communicate with a background page. Sounds like a pain to me. I would suggest you go this route only if there is no other ways possible.
// Importation of jQuery.js
var scriptImport = document.createElement('script');
scriptImport.type = 'text/javascript';
scriptImport.src= chrome.extension.getURL('js/jquery.js');
head.appendChild(scriptImport);
// Injection of onClick script
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML =
"document.addEventListener('click', function()" +
"{ if(document.getElementById('dropMenu')) {" +
"$('#dropMenu').slideUp(800, function() {" +
"$(this).remove();" +
"});" +
"}});";
I've finally done this, it works :)

Categories