I want to load js on the fly which is happening but the one more js file which is included in index is loading before (file i am loading dynamically) is there way to fix the order
i am adding global.js dynamically and i want variable declared in global.js shoud be initialised before dynamicjs.DynamicJs is loaded
------------- Index.html -------------
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons"
data-sap-ui-theme="sap_goldreflection" >
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<script src="js/dyn.js"></script>
<script></script>
<script>
sap.ui.localResources("dynamicjs");
var view = sap.ui.view({id:"idDynamicJs1", viewName:"dynamicjs.DynamicJs", type:sap.ui.core.mvc.ViewType.JS});
view.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
function loadScript(url){
var xhrObj = createXMLHTTPObject();
// open and send a synchronous request
xhrObj.open('GET', url, false);
xhrObj.send('');
var e = document.getElementsByTagName("script")[1];
var d = document.createElement('script');
d.src = url;
d.type = 'text/javascript';
d.async = false;
d.defer = false;
e.parentNode.insertBefore(d,e);
}
function addScriptDynamically(){
loadScript('js/global.js'+'?scheme=12345');
}
function createXMLHTTPObject(){
var xmlhttp=new XMLHttpRequest();
if( typeof xmlhttp == 'undefined' || xmlhttp == null )
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlhttp;
}
/*call function */
addScriptDynamically();
Why won't you try to load script with jQuery.getScript()
http://api.jquery.com/jQuery.getScript/
If you want compatibility with other libraries like prototype or mootools you can set jQuery.noConflict()
Related
I am using W3-Schools "include-html" https://www.w3schools.com/howto/howto_html_include.asp
It states that you can use multiple snippets. My plan was to include a header and a footer for each page by using this method.
On my index.html page I have this:
<!doctype html>
<html lang="en">
<!--Include Content-->
<script src="assets\scripts\include_content.js">
</script>
</head>
<body>
<header>
<div include-html="header.html"></div>
</header>
<footer>
<div include-html="footer.html"></div>
</footer>
<!--Scripts-->
<script>
includeHTML();
</script>
</body>
</html>
The scripts are a direct copy and paste from W3 (with minor changes to attribute names):
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain attribute:*/
file = elmnt.getAttribute("include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
elmnt.innerHTML = this.responseText;
}
if (this.status == 404) {
elmnt.innerHTML = "Page not found.";
}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
};
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
I can get the footer to run if I delete the include-html="header.html" so I know the linking is there. But I can not get both footer and header to run.
Both footer and header pages are currently identical except for the message so I know where the message is coming from.
Can you see if I am missing something or why the second <div include-html="footer.html"></div> is not working?
For all the reasons I mentioned in my comments to your question, you should just abandon the W3 Schools approach.
The simplest solution is to just use HTML <iframe> elements and no JavaScript whatsoever:
<!doctype html>
<html lang="en">
<head>
<title>Page Title Here</title>
<meta charset="utf-8">
</head>
<body>
<header>
<iframe src="header.html"></iframe>
</header>
<footer>
<iframe src="footer.html"></iframe>
</footer>
</body>
</html>
But, if you do need a JavaScript solution, using AJAX (XMLHttpRequest) is correct, but with the modern syntax, rather than what W3 Schools shows:
function includeHTML(fileName, destination) {
let xhr = new XMLHttpRequest();
// Establish the callback:
xhr.onreadystatechange = function () {
// Is the response ready?
if (this.readyState == 4) {
// Was the response successful?
if (this.status == 200) {
destination.innerHTML = this.responseText;
} else {
console.log("Response was received but not successful.");
}
} else {
console.log("Response is not ready.");
}
}
// Initiate the request:
xhr.open("GET", fileName, true);
xhr.send();
}
// Call the function with the file to include and a reference to the
// element to populate with the contents
includeHTML("header.html", document.querySelector(".header"));
includeHTML("footer.html", document.querySelector(".footer"));
<!doctype html>
<html lang="en">
<head>
<title>Page Title Here</title>
<meta charset="utf-8">
</head>
<body>
<header>
<div class="header"></div>
</header>
<footer>
<div class="footer"></div>
</footer>
<!--Reference and load your scripts just before the closing
body tag so that by the time the HTML parser reaches
this point in the document, all the HTML will have been
parsed into memory. -->
<script src="assets\scripts\include_content.js"></script>
</body>
</html>
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.
Here's my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>News Site</title>
<script>
window.document.onload = function () {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "cdcatalog.xml", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var xmlDoc = this.responseXML;
console.log(xmlDoc);
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "<br/>" + xmlDoc.getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
} else {
document.getElementById("demo").innerHTML = "Can't show it.";
}
}
}
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>
I am a beginner in using Ajax and this is my first project. I checked with the format, even validated it with W3 Validator, and it doesn't seem to work.
Nothing is showing on the page. It's completely blank.
Can anyone point out my mistake please?
The document object does not have an onload property. Using that style of event handler assignment, you are looking for window.onload.
I have two script files - one is perl-cgi and the other is javascript. Inside the cgi script I have written the Javascript function for retrieving data from a text file (using ajax). I then pass the contents of the data into another function called main_function(). This writes into the javascript file (seq_new.js). When I load the page, the console.log reports main_function was not defined. Then I refresh the page and the result displays. I don't know why it behaves this way.
The Perl script as follows:
#!/usr/bin/perl
print "Content-type:text/html\n\n";
use CGI;
my $a= new CGI;
my $processId = $a->param("processId");
.
.
my $file_path = "/$processId/$file_name[1]";
print <<HTML;
<!DOCTYPE html>
<html>
<head>
<title>RepEx - Result</title>
<script type="text/javascript" src="/min.js"></script>
</head>
<body>
<script>
file_load("$file_path","$filename");
function file_load(f1,f2)
{
var fileNm = f2;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
var pt = xhttp.responseText;
main_function(pt,fileNm,"$file_path",$file_cnt,"$head_st");
}
};
xhttp.open("GET", f1, true);
xhttp.send();
}
</script>
<script type="text/javascript" charset="utf-8" src='/seq_new.js'> </script>
</body>
</html>
My javascript file contains this:
function main_function (a,file_seq,main_file,fle_cnt,header_set)
{
.
..
}
The problem I am encountering
Loading the page for the first time, the console.log reports that the main_function was not defined and no results are displayed. After refreshing the page (by pressing F5 or clicking the reload button), the result is displayed.
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>