My source code :
<!doctype html>
<html>
<head>
<title>onload test</title>
<link type="text/css" rel="stylesheet" href="spot.css" media="screen" />
</head>
<body>
<h1>Welcome Page</h1>
<script>
debugger;
function constructScripts(url, callBack) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
if (script.readyState) {
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null; callBack();
}
};
}
else {
script.onload = callBack;
}
}
</script>
<script>
debugger;
myCallBack = function () {
alert(this.src + "loaded");
}
constructScripts("files1", myCallBack);
constructScripts("files2", myCallBack);
constructScripts("files3", myCallBack);
</script>
</body>
</html>
this.src is undefined here. I guess this should be an 'script' object which supposed to have its src property so that I can read the filename. Who is this here? And also when I view the page source these scripts were not included in the header() section. Why is it so?
this.src is undefined here.
It shouldn't be… It is defined earlier: script.src = url
I guess this should be an 'script' object which supposed to have its src property so that i can read the filename. Who is 'this' here?
The script element upon which the onload or readystatechange event fires
And also when i view the page source these scripts were not included in the header() section. Why is it so?
Because you are looking at the page source, not a serialisation of the live DOM after it has been manipulated by JavaScript.
When you call you callBack function, pass it the script object like callBack(script). Modify the callBack function like
myCallBack = function (script) {
alert(script.src + "loaded");
}
View source does not show dinamically loaded elements.
You need to extend your function using prototype.
Element.prototype.MyMethod = function(){}
Look at your edited code
<!doctype html>
<html>
<head>
<title>onload test</title>
<link type="text/css" rel="stylesheet" href="spot.css" media="screen" />
</head>
<body>
<h1>Welcome Page</h1>
<script>
Element.prototype.MyMethod = function(){}
function constructScripts(url, callBack) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
script.MyMethod = callBack;
document.getElementsByTagName("head")[0].appendChild(script);
if (script.readyState) {
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
script.MyMethod();
}
};
}
else {
script.onload = callBack;
}
}
</script>
<script>
myCallBack = function () {
alert(this.src + "loaded");
}
constructScripts("files1", myCallBack);
constructScripts("files2", myCallBack);
constructScripts("files3", myCallBack);
</script>
</body>
</html>
Related
I do a simple check if js file exists. If not, I try to load it dynamically before other scripts from bottom of a page are loaded. Is it possible to do? Here is fiddle where bottom script is executed before thus giving errors.
https://jsfiddle.net/vnfxus56/1/
thank you.
<div id="top">top</div>
<script>
doesFileExist('https://ajax.googleapis.com/ajax/libs/nonexistingfile.js');
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status == "404") {
console.log("File doesn't exist");
var script = document.createElement('script')
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js'
document.head.append(script)
return false;
} else {
console.log("File exists");
return true;
}
}
</script>
<script>
//this is printed out of a variable as a bunch of inline jquery code
$("#top").fadeOut();
</script>
below I posted the code that could await until the "xhr" request is finished. I used the "async functions" concept in javascript that you can read more about it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
function afterLoad() {
console.log('DOM fully loaded and parsed');
$("#top").fadeOut();
}
#top {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>xhr</title>
<link rel="stylesheet" href="style.css">
</head>
<body onload="afterLoad()">
<!-- using "onload" method is necessary to run the script after finishing "xhr" -->
<div id="top">top</div>
<script>
let urlToFile = 'https://ajax.googleapis.com/ajax/libs/nonexistingfile.js';
function doesFileExist(urlToFile) {
return new Promise(resolve => {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status == "404") {
console.log("File doesn't exist");
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js';
script.setAttribute("async", "");
console.log(script);
document.body.append(script);
// your custom script file
var script2 = document.createElement('script');
script2.src = 'myscript.js'; // define the address of your javascript file.
script2.setAttribute("async", "");
document.body.append(script2);
resolve(false);
} else {
console.log("File exists");
resolve(true);
}
});
}
async function asyncCall(urlToFile) {
console.log('starting');
const result = await doesFileExist(urlToFile);
console.log(result);
console.log("finished");
}
asyncCall(urlToFile);
</script>
</body>
</html>
I think it is useful to mention that I changed your code from two "script" tags to only "one" and used "two" functions in it. one of them works on "xhr" request and adding script tags, and the other forces the code to wait until the xhr request is finished. I added "$("#top").fadeOut();" part of your code to a separate script code that is in the same directory and appended the script tag in first function.
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>
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>
I am loading my JavaScript files dynamically in the page:
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var script1 = document.createElement('script'),
script2 = document.createElement('script'),
script3 = document.createElement('script');
script1.type = 'text/javascript';
script1.src = 'myScript1.js';
script2.type = 'text/javascript';
script2.src = 'myScript2.js';
script3.type = 'text/javascript';
script3.src = 'myScript3.js';
document.body.appendChild(script1);
document.body.appendChild(script2);
document.body.appendChild(script3);
}
</script>
</head>
<body>
</body>
</html>
I need to know when these Scripts loaded completely. Is there any workaround or code snippets to do this?
before document.body.appendChild
scrimpt1.addEventListener('load', function() { console.log('loaded'); });
obviously you'll want to do "something useful" instead of the simple console.log I've shown
BUT ... this isn't always realiable
try this
var numScripts;
function scriptLoaded() {
numScripts --;
if(numScripts == 0) {
console.log('huzzah all scripts loaded');
}
}
then, your code
window.onload = function () {
var script1 = document.createElement('script'),
script2 = document.createElement('script'),
script3 = document.createElement('script');
numScripts = 3;
script1.type = 'text/javascript';
script1.src = 'myScript1.js';
script2.type = 'text/javascript';
script2.src = 'myScript2.js';
script3.type = 'text/javascript';
script3.src = 'myScript3.js';
document.body.appendChild(script1);
document.body.appendChild(script2);
document.body.appendChild(script3);
}
at the end of each of your scripts, put something like
if(windows.scriptLoaded) {
scriptLoaded();
}
Use a callback
function greetFinished() {
alert("Do stuff finished");
}
function greet (greeting, callback) {
alert(greeting)
callback (options);
}
greet("Hello",greetFinished);
greetFinished will be called inside the greet function greetFinished is a callback it will be called after the alert.