I was trying to make a button that will run a JavaScript when it was clicked.First, my script was like this
<script>
function myFunction()
{
alert('Invalid username or password. Please try again.')
}
</script>
<input onclick="myFunction()" type="submit" value="Generate" href="submit.php" >
It works, and a popup appear.But when I try to call JavaScript from another site, nothing happens.
<script>
function myFunction()
{
document.body.appendChild(document.createElement('script')).src='https://raw2.github.com/BlackEagleBCC/Script/master/myscript.js';
}
</script>
<input onclick="myFunction()" type="submit" value="Generate" href="submit.php" >
You need to include the js file once event occurs.
Please refer to this link, it demonstrates dynamic including js and css.
Add html code
<ul>
<li>Load "myscript.js"</li>
<li>Load "mystyle.css"</li>
</ul>
Then js code
function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
Code for myscript.js
var petname="Spotty"
alert("Pet Name: " + petname)
Code for mystyle.css
#ul li{
background-color: lightyellow;
}
Similar to this :
You can call loadjscssfile('myscript.js','js') inside your button onclick() event handler.
Update:
Try this out:
<a id='myScript' type="submit" href="submit.php" > Generate </a>
Script:
<script type="text/javascript">
var myScript = document.getElementById('myScript');
myScript.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://raw2.github.com/BlackEagleBCC/Script/master/myscript.js";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
EDITED: The below solution might not be what you are looking for now.
I have been using this,a solution which I found from stackoverflow itself.
function loadScripts(array,callback){
var loader = function(src,handler){
var script = document.createElement("script");
script.src = src;
script.onload = script.onreadystatechange = function(){
script.onreadystatechange = script.onload = null;
handler();
}
var head = document.getElementsByTagName("head")[0];
(head || document.body).appendChild( script );
};
(function(){
if(array.length!=0){
loader(array.shift(),arguments.callee);
}else{
callback && callback();
}
})();
}
This will help you create script tags.
loadScripts([
"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js",
"https://raw2.github.com/BlackEagleBCC/Script/master/myscript.js"
],function(){
alert('Scripts have been loaded successfully');
});
Edited:
I have used this method when I needed to build script tags and get a callback after everything loads fine. (These things come handy :) )
https://stackoverflow.com/a/1867135/3222041
Related
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>
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);
}
When I click a button I want a script that I have on my computer to run. It can be a simple print "Hello World".
How do I do that ? What I have is this :
I don't have the litle idea how do this could be done please can you help?
HTML
<input class="buttonRun" type="button" value="Run" id="btnRun"/>
function runScript() {
}
$("#btnRun").click(function () {
runScript();
});
Python
print ("Hello World");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="buttonRun" type="button" value="Run" id="btnRun"/>
<script>
function runScript() {
alert('Hello World!');
}
$("#btnRun").click(function () {
runScript();
});
</script>
Here you can pass the scriptUrl to this function and it will load all the methods and variable that has been wriiten in the script file.
loadExternalScript(scriptUrl: string) {
return new Promise((resolve, reject) => {
const scriptElement = document.createElement('script')
scriptElement.src = scriptUrl
scriptElement.onload = resolve
document.body.appendChild(scriptElement)
});
}
may this help for you:
You may dynamically need to append the script in your tag like this
try this
function runScript(){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange = function () {
if (this.readyState === 'complete' || this.readyState === 'loaded') {
callback();
}
};
script.onload = callback;
script.src = 'Your scripts path ';
head.appendChild(script);
}
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>
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>