On a webpage, once images have been downloaded and rendered, I need to determine an image's file size (kb) within the browser context (so I could display that info on the page, just below the image)
The easiest way is probably with a HEAD request returning the Content-Length:
function fileSize(img, func) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', img.src, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
func(xhr.getResponseHeader('Content-Length'))
}
}
xhr.send()
}
Usage
fileSize(imgNode, function(size) {
// ...
})
Related
I am using xhlhttprequest to load an external html file. However I am trying to figure out how to load only a speicific DIV from that html file.
My external page is helpFile.html- it has dozens header <DIV>s, an each header DIV is a specific help section. On different pages, I want to be able load a specific section? How could I do this? As an example, on the dashboard.html page is a help ? icon, that when the user clicks on it, it will load just the helpFile.html#dashboard section out of the main helpFile.html page - the content would be loaded into a bootstrap modal.
Here is my code to retrieve the entire page, but how can I just retrieve the needed section.
<script>
var request;
function sendInfo() {
var url = "helpFile.html";
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to connect to server");
}
}
function getInfo() {
if (request.readyState == 4) {
var val = request.responseText;
document.getElementById('helpModal').innerHTML = val;
}
}
</script>
Use DOMParser and look for the element
if (request.readyState == 4 && request.status == 200) {
var parser = new DOMParser();
var doc = parser.parseFromString(request.responseText;, "text/html");
var dashboardElement = doc.querySelector("#dashboard");
document.getElementById('helpModal').innerHTML = dashboardElement.innerHTML;
}
I have an AJAX call whose reponse will feed some HTML into a DIV's innerHTML.
The response can contain images, and I'd like to have all these images loaded before my custom loading-div will hide.
I want to do this in vanilla JS. Unfortunately every question I've found here so far does it via jQuery.
I've tried adding an onload Event Listener to both the DIV and the xhttp object, but neither works. The loader disappears as soon as the HTML code is received and inserted, and then the user can witness each image loading individually.
document.getElementById("pageloader").className = "fadein";
var poststring = "&page="+encodeURIComponent(page);
var xhttp = new XMLHttpRequest();
xhttp.addEventListener("load", function() {
document.getElementById("pageloader").className = "fadeout";
});
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML = this.responseText;
}
};
xhttp.open("POST", "myajax.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(poststring);
I have a situation where if browser window is closed then i need to make an XmlHttpRequest and show the result in a pop before the window is closed. But in my current code the browser doesn't wait for XmlHttpRequest to complete as it is asynchronous and closes the window. how can i open a pop before the browser closes itself.
var xhr = new XMLHttpRequest();
window.onbeforeunload = sendRequest();
//method to send the request to server
function sendRequest(){
xhr.open('GET', "https://www.google.co.in/search?q=java", true);
xhr.send();
xhr.onreadystatechange = processRequest;
}
//method to process the output
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var xmlDoc = xhr.responseText;
alert(xmlDoc);
}
}
the result(alert) should be visible before window is closed.
You can make change little bit in your JS codes:
Referred from documentation link: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Example
where we need to cancel the event as stated by the browser, events like refreshing/ reloading a page or going to back page.
function sendRequest(event){
event.preventDefault();
event.returnValue = '';
var __type= event.currentTarget.performance.navigation.type;
// __type === 1 || __type === 0 : comes when Browser refresh button is clicked...
// __type === 2 : Browser back button is clicked
if(__type === 1 || __type === 0 || __type ==2){
// write here your AJAX request code or you can create a function for AJAX request & call up that function
xhr.open('GET', "https://www.google.co.in/search?q=java", true);
xhr.send();
xhr.onreadystatechange = processRequest;
}
}
//method to process the output
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var xmlDoc = xhr.responseText;
alert(xmlDoc);
}
// here you can write a code to close the browser window
}
For the last hour or so, I've been trying to solve a problem, which came up when I tried to change html of an element from XMLHttpRequest.
xhr.open('GET', url);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(document.getElementById('notifications-navbar').innerHTML);
document.getElementById('notifications-navbar').innerHTML = xhr.responseText;
console.log(xhr.responseText);
console.log(document.getElementById('notifications-navbar').innerHTML);
} else {
console.log('error');
}
};
xhr.send();
The output of the console logs were:
pastebin
So in the console.log we can see the change to the innerHTML was made, however there is no change whatsoever when I have a look on the elements via Chrome inspect and also there is no change in the browser. I even tried to remove every other JS scripts that were being loaded and just make a simple change of the innerHTML outside of XHLHttpRequest, but that didn't help too. Please if you could help I would be really happy.
Not sure what your EndPoint URL is , but I wrote this for you and it works just fine. Hope this can help you!
HTML
<div id = "notifications-navbar"></div>
Javascript
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "http://jsonplaceholder.typicode.com/posts";
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(document.getElementById('notifications-navbar').innerHTML);
document.getElementById('notifications-navbar').innerHTML = xhr.responseText;
console.log(xhr.responseText);
console.log(document.getElementById('notifications-navbar').innerHTML);
} else {
console.log('error');
}
};
xhr.send();
Okay, sorry guys, I found my mistake, I had in my HTML two elements with ID notifications-navbar and only the first one was being changed. Thanks for your help anyway.
I am working on getting a dynamic page set up on my site where clicking a "More Info" button triggers a loadBCW.js script which updates a <div>'s innerHTML using a text file saved elsewhere. I've got that working perfectly using this loadBCW.js:
document.getElementById("loadBCW").addEventListener('click',function(){
var url = "/wp-content/themes/DICE/js/descriptionBCW";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
document.getElementById("demo").innerHTML = url;
}, false);
My issue is, when I click one of the "More Info" buttons in order to change the <div>'s innerHTML, it will flash the variable url in the <div>, then the correct elements overwrite it.
How can I instruct js to NOT flash the variable url onscreen before actually updating the <div>?
Maybe get rid of the code that sets the div content to be the URL in the first place? I've commented out the line you should remove:
document.getElementById("loadBCW").addEventListener('click',function(){
var url = "/wp-content/themes/DICE/js/descriptionBCW";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
// document.getElementById("demo").innerHTML = url;
}, false);
You're making an asynchronous request to an external source, so the code inside the xhttp.onreadystatechange won't run until the file was successfully retrieved. There's not really anything you can do about this other than optimize your site to run faster than . So if you don't want the URL to be visible, there's no point in setting it in the first place.
However, this would be even worse if it was a sync request, as not only will it slow you performance, but since document.getElementById("demo").innerHTML = url; is after your function, it is guaranteed to end by replacing the content with the URL.