I'm trying to embedd two html documents in another using javascript. The problem I am having is that the onload event does not fire on the embedded document.
paper.htm has several div tags and should contain curve.htm but in curve.htm the onload event is not firing
paper.htm
<html>
<head>
<title>Curve</title>
<script>
(function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'curve.htm', true);
xhr.onreadystatechange = function () {
if (this.readyState !== 4) return;
if (this.status !== 200) return;
document.getElementById('chartBlock').innerHTML = this.responseText;
}
xhr.send();
})();
</script>
</head>
<body>
<div id="paper">
<div id="border">
<div id="chartBlock"></div>
<div id="titleBlock"></div>
</div>
</div>
</body>
</html>
curve.htm (partial)
<html>
<head>
<script src="File:///Temp/curveData.js" type="text/javascript"></script>
<script>
window.onload = init; //this never fires!
function init() { //... }
</script>
<body>
<canvas id="chartCanvas" width="954" height="625"></canvas>
</body>
</html>
I have tried:
Using jquery to load the html document (many examples here on SO).
Putting onload in the body tag of the html document (curve.htm)
tried with jquery:
<script>
$(function () {
$("#chartBlock").load("curve.htm");
$("#titleBlock").load("titleblock.htm");
});
</script>
tried with html:
<body onload="init()">
Any other ideas to look into would be very much appreciated. Thanks
Because the document will not be loaded...
What you are doing could be achieved with iframes. With an iframe, you are loading a full html document, which will be parsed as such. With the $.load function, you will just bluntly insert html, which will be parsed as <body>'s children. Meaning; the <head>, <meta> tags etc. will be ignored by all/proper browsers, because they should only occur inside the head of a document. Simplified, your output would be:
<html>
<head>
<!-- whatever -->
</head>
<body>
<div id="chartBlock">
<html>
<!-- What?! Another html tag?! -->
</html>
</div>
<div id="titleBlock">
<html>
<!-- And another one... -->
</html>
</div>
</body>
</html>
So, what you want to do, is loading only the contents, what would be inside the <body> tag, and use the success callback of the $.load function to do whatever you want to do if the contents are inserted in your document.
You could still load the page without using iframes, you just need to go about it a little differently. Basically since you're putting an html page inside of a div, the scripts on that page never get rendered.
To make it work, the scripts need to be inserted into the parent documents head.
Get scripts and insert them into head:
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script'),
data;
script.type = 'text/javascript';
...
data = document.getElementById('chartBlock')
.getElementsByTagName('script').item(0).innerHTML;
try {
script.appendChild(document.createTextNode(data));
} catch(e) {
script.text = data;
}
head.insertBefore(script, head.firstChild);
head.removeChild(script);
Retrigger Load Event
var event = new Event('load');
//place after script has been inserted into head
window.dispatchEvent(event);
Using your example above:
curve.htm
<html>
<head>
<script src="File:///Temp/curveData.js"></script>
<script>
window.onload = init; //this will now fire
function init() { alert('loaded'); }
</script>
</head>
<body>
<canvas id="chartCanvas" width="954" height="625"></canvas>
</body>
</html>
paper.htm
<html>
<head>
<title>Curve</title>
<script>
(function () {
var xhr = new XMLHttpRequest(),
event = new Event('load'),
//since the onload event will have already been triggered
//by the parent page we need to recreate it.
//using a custom event would be best.
head = document.getElementsByTagName('head')[0],
script = document.createElement('script'),
data;
script.type = 'text/javascript';
xhr.open('GET', 'curve.htm', true);
xhr.onreadystatechange = function (){
if (this.readyState !== 4) return;
if (this.status !== 200) return;
document.getElementById('chartBlock').innerHTML = this.responseText;
data = document.getElementById('chartBlock')
.getElementsByTagName('script').item(0).innerHTML;
//we're extracting the script containing the
//onload handlers from curve.htm,
//note that this will only cover the first script section..
try {
// doesn't work on ie
script.appendChild(document.createTextNode(data));
} catch(e) {
script.text = data;
}
head.insertBefore(script, head.firstChild);
head.removeChild(script);
window.dispatchEvent(event);
//once the scripts have been rendered,
//we can trigger the onload event
}
xhr.send();
})();
</script>
</head>
<body>
<div id="paper">
<div id="border">
<div id="chartBlock"></div>
<div id="titleBlock"></div>
</div>
</div>
</body>
</html>
Related
I added a Cookies Consent banner. The requirement is that https://cdn.cookielaw.org/consent/c4337328/OtAutoBlock.js loaded before any other script. I now wonder if appendChild is the right choice. Will it load OtAutoBlock at the exact position I wrote it or will it append the script to the end of the tag (which would be too late). It has to be the first script that's loaded.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- OneTrust Cookies Consent Notice -->
<script type="text/javascript">
if ("%REACT_APP_COOKIE_BAR%" === "true") {
var otAutoBlock = document.createElement("script");
otAutoBlock.setAttribute("type", "text/javascript");
otAutoBlock.setAttribute("src", "https://cdn.cookielaw.org/consent/c4337328/OtAutoBlock.js");
var otSDKStub = document.createElement("script");
otSDKStub.setAttribute("type", "text/javascript");
otSDKStub.setAttribute("src", "https://cdn.cookielaw.org/scripttemplates/otSDKStub.js");
otSDKStub.setAttribute("charset", "UTF-8");
otSDKStub.setAttribute("data-domain-script", "c4337328");
document.getElementsByTagName("head")[0].appendChild(otAutoBlock);
document.getElementsByTagName("head")[0].appendChild(otSDKStub);
function OptanonWrapper() { }
}
</script>
<script type="text/javascript">
/* [Should load after OtAutoBlock loads to avoid tracking before consent was given] */
</script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
document.head.appendChild(script) will add it to the end of the <head> tag, so it will load after all other scripts. You can do two things:
You load it with appendChild at the end, and have all your other scripts with a defer attribute, like this: <script defer> /* something */ </script> The defer forces a script to execute after the page is loaded, but if you load the OtAutoBlock without a defer, it will run before the others. The only thing to note is that defer will cause the scripts not to run last, but after the entire page loads, which includes CSS stylesheets, other JavaScripts, icons, images, HTML content, XHR requests in <script> tags, etc.
<script>
const load = true; // your stuff here
if (load)
{
const script = document.createElement('script');
window.hasRunned = false;
script.text = 'alert(\'OtAutoBlock running.\'); window.hasRunned = true;';
document.head.appendChild(script);
}
</script>
<script defer>
alert('Another script. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
<script defer>
alert('And yet another. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
You use insertBefore to add it before the other scripts, so it will run before them. No need to use defer with this method. This might be what you want if you need the scripts to run before the page loads.
<script>
const load = true; // your stuff here
if (load)
{
let script = document.createElement('script');
window.hasRunned = false;
script.text = 'alert(\'OtAutoBlock running.\'); window.hasRunned = true;';
document.head.insertBefore(script, document.head.children[0]);
}
</script>
<script>
alert('Another script. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
<script>
alert('And yet another. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>
With this HTML the function myFunc() can be executed. https://myurl.de/myjs.js has the function myFunc in it.
<head>
<script type="text/javascript" src="https://myurl.de/myjs.js"></script>
<body>
<script type="text/javascript">
myFunc();
</script>
</body>
</head>
But with the second HTML I get an Error: Uncaught ReferenceError: myFunc is not defined.
https://myurl.de/settingsFile.js is a file that includes this url in a var: https://myurl.de/myjs.js so basically SettingsFile.UrlToMyJS is this https://myurl.de/myjs.js
<head>
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript" id="myid"></script>
</head>
<body>
<script type="text/javascript">
document.getElementById('myid').src = SettingsFile.UrlToMyJS;
myFunc();
</script>
</body>
When I console.log(document.getElementById('myid')) this is the output:
<script type="text/javascript" id="myid" src="https://myurl.de/myjs.js></script> which is correct. It looks exactly like the script in the head of the first html (with the difference that it has the id="myid").
Yet it does not work. Why and how can I fix it?
settingsFile.js:
var defaultURL = 'https://myurl.de/';
var SettingsFile = {
UrlToMyJS : defaultURL + 'myjs.js',
}
The reason it's not working is that you can't add a src to a script element that's already in the DOM — or rather, doing so doesn't do anything. The script element has already been processed.
Instead, create it and then append it:
var script = document.createElement("script");
script.onload = function() {
myFunc();
};
script.src = SettingsFile.UrlToMyJS;
document.head.appendChild(script);
// If you need to support IE8, use the following instead of the previous line:
//document.getElementsByTagName("head")[0].appendChild(script);
That waits for the script to load, then calls myFunc (which should exist by then).
Also note that as I and Jeremy pointed out in the comments, body doesn't go in head, it goes after. It's also generally best to put script tags at the end of body (if you're not using async or defer attributes on them or type="module"). So in all, something like:
<head>
<!-- head stuff here -->
</head>
<body>
<!-- content here -->
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript">
var script = document.createElement("script");
script.onload = function() {
myFunc();
};
script.src = SettingsFile.UrlToMyJS;
document.head.appendChild(script);
// If you need to support IE8, use the following instead of the previous line:
//document.getElementsByTagName("head")[0].appendChild(script);
</script>
</body>
Another option is to use document.write. This sort of thing may be the last at-least-partially appropriate use of document.write during the main parsing of the page:
<head>
<!-- head stuff here -->
</head>
<body>
<!-- content here -->
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript">
document.write('<script src="' + SettingsFile.UrlToMyJS + '"><\/script>');
</script>
<script>
myFunc();
</script>
</body>
You can try creating a element and then appending it to your title
For Example (script code) :
var script = document.createElement("script");
script.src = "YOUR_SCRIPT_SRC_HERE";
document.getElementsByTagName('head')[0].appendChild(script);
Here I am creating a new tag in html and then appending it to the head of your html. Even as T.J. Crowder mentioned in the comment try removing your body from the head
While converting a script to not require jQuery, I've discovered that if I load my content (a partial html page with html and javascript) via XMLHttpRequest, the javascript in the partial page does not work. But if I load the partial using jQuery.load, it does work.
I've tried digging through jQuery's load function to see if it's doing anything special and nothing jumped out at me. I've been banging my head against the wall and searching for an answer for a couple of days now to no avail.
What am I doing wrong/how can I make it work like it does when loaded with jQuery.load?
EDIT
I got the XMLHttpRequest method to work by splitting out out my javascript from the html in the fragment and loading the javascript using the suggested technique here: https://stackoverflow.com/a/11695198/362958. However, that still does not provide an explanation of why jQuery.load works. Is jQuery umtimately parsing the HTML and doing the same thing for any scripts it finds within the content it loads?
I've set up a plunker (https://plnkr.co/edit/wE9RuULx251C5ARnUbCh) with the following code that demonstrates the issue. Note: once you load the fragment with jQuery, it will continue to work and you'll have to restart the plunk for the XMLHttpRequest method to fail again.
index.html:
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h3>Buttons</h3>
<div>
<input type="button" value="Load with XMLHttpRequest" onclick="loadXMLDoc('ajaxContentDiv', 'fragmentToLoad.html');"> (Links do not work if loaded this way... Script from fragmentToLoad.html not loaded in DOM?) <br/><br/>
<input type="button" value="Load with JQuery" onclick="jQuery('#ajaxContentDiv').load('fragmentToLoad.html');"> (Links will work if loaded this way)
</div>
<br/>
<br/>
<br/>
<div id="ajaxContentDiv">Content will load here...</div>
</body>
</html>
script.js:
function loadXMLDoc(targetDivName, url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById(targetDivName).innerHTML = xmlhttp.responseText;
}
}
};
xmlhttp.send();
}
fragmentToLoad.html:
<div id="divToBeUpdated">
<span id="stringBox">String here</span>
</div>
<br/>
<h3>Links</h3>
<div>
Link 1<br>
Link 2<br>
Link 3<br>
</div>
<script>
function updateDiv(string){
var stringBox = document.getElementById('stringBox');
stringBox.innerHTML = string;
}
</script>
You can use single .html file, and you are on the correct track by splitting the html content - though you can also split the html content of a single file, rather than requesting two files. #Barmar explains the functionality of jQuery's .load() method at this comment.
script.js
function loadXMLDoc(targetDivName, url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
// create a `div` elemenent, append response to `div` element
// get specific elements by `id`, append `script` element to `document.body`
var content = document.createElement("div");
content.innerHTML = xmlhttp.responseText
var div = content.querySelector("#htmlContent");
var contentScript = content.querySelector("#contentScript");
var script = document.createElement("script");
script.textContent = contentScript.textContent;
document.getElementById(targetDivName).innerHTML = div.innerHTML;
document.body.appendChild(script);
}
}
};
xmlhttp.send();
}
fragmentToLoad.html
<div id="htmlContent">
<div id="divToBeUpdated">
<span id="stringBox">String here</span>
</div>
<br/>
<h3>Links</h3>
<div class="links">
Link 1
<br>
Link 2
<br>
Link 3
<br>
</div>
</div>
<script type="text/javascript" id="contentScript">
function updateDiv(string) {
var stringBox = document.getElementById('stringBox');
stringBox.innerHTML = string;
}
// attach `click` event to `.link a` elements here
var links = document.querySelectorAll(".links a");
for (var i = 0; i < links.length; i++) {
(function(link, i) {
console.log(i)
link.addEventListener("click", function(e) {
e.preventDefault();
updateDiv("Hello World " + i)
})
})(links[i], i)
}
</script>
plnkr https://plnkr.co/edit/7fLtGRSV7WlH2enLbwSW?p=preview
I am trying to figure out the location of the script tag the current javascript is running in. What is really going on is that I need to determine from inside a src'd, dynamically inserted javascript file where it is located in the DOM. These are dynamically generated tags; code snippet:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>where am i?</title>
<script type="text/javascript" charset="utf-8">
function byId(id) {
return document.getElementById(id);
}
function create_script(el, code) {
var script = document.createElement("script");
script.type = "text/javascript";
script.text = code;
el.appendChild(script);
}
</script>
</head>
<body>
<div id="find_me_please"></div>
<script>
create_script(byId("find_me_please"), "alert('where is this code located?');");
</script>
</body>
</html>
You could give the script an id tag, like this dude does...
You can use document.write to create a dummy DOM object and use parentNode to escape out. For example:
<script>
(function(r) {
document.write('<span id="'+r+'"></span>');
window.setTimeout(function() {
var here_i_am = document.getElementById(r).parentNode;
... continue processing here ...
});
})('id_' + (Math.random()+'').replace('.','_'));
</script>
This assumes you don't actually have control of the <script> tag itself, such as when it's inside a <script src="where_am_i.js"></script> - if you do have control of the <script> tag, simply put an ID on it, as in:
<script id="here_i_am">...</script>
If you are just running this on page load, this works
<script>
var allScripts = document.getElementsByTagName('script');
var thisScript = allScripts[allScripts.length];
alert(thisScript);
</script>