How do I make .load() wait till everything is fully loaded? [duplicate] - javascript

I have a Python script that is doing some manipulation on a JPEG image. I pass some parameters to this script and call it from my HTML page. The script returns an img src="newimage.jpg tag.
I know how to wait for the reply from the script but I don't know how to tell when the image is fully loaded (when it is, I want to display it). What I get now is the image loading slowly so the user is seeing this "loading" process. Instead, I want to have a msg telling the user to wait while the image is loading, only then I want to display the image.

You can dynamically create a new image, bind something to its load event, and set the source:
$('<img>').bind('load', function() {
$(this).appendTo('body');
}).attr('src', image_source);

Image Loading
Wait for ajaxRequest

The other answers have mentioned how to do so with jQuery, but regardless of library that you use, ultimately you will be tying into the load event of the image.
Without a library, you could do something like this:
var el = document.getElementById('ImgLocation');
var img = document.createElement('img');
img.onload = function() {
this.style.display = 'block';
}
img.src = '/path/to/image.jpg';
img.style.display = 'none';
el.appendChild(img);

Related

How to show loader overlay until image is loaded on webpage?

I want to make a loading overlay, but instead using setTimeout I would like to show the "loader" until the first image is fully loaded on the webpage. ( After that, I would like to use lazy image loading )
Until now I used setTimeout, but it's not working really well. I can set a bigger time, but now there is a "gap" between the loader and when the image appears.
The picture urls are fetched from a wordpress API and I'm using template.
What I want is to show the "loading" overlay until the first image is fully loaded, so users don't see the blank state.
var img = document.querySelector("#img");
img.onload = function(){
document.getElementById("loading").style.display = "none"
}
I can't use jQuery because it's for a school project. I tried all the alternatives I found here by adding a console.log("loaded") when it's loaded, but nothing seems to work.
Maybe set the img.src after you defined onload
let img = document.createElement('img');
img.onload = function(){}
img.src = "url"

Function firing before images has finished loading

I'm trying to get a pre loader screen to work but am hitting a roadblock.
My goal: To have the loading animation/divs dissapear when the image has finished loading.
I've tried to accomplish this with a simple .ready function and still the function that removes the loading animation fires white the image is still loading and the viewer will see the image load in real time.
$("#defaultImage").ready(function(){
TweenMax.to(["#backgroundLoad","#loadBoxes"],1,{alpha:0,delay:0.75});
console.log('Page has loaded');
});
Is this incorrect? I thought that this will wait for the entire page(images included) to load and then fire the function inside it.
I've tried the below too and it doesn't seem to fire the console.log at all
document.getElementById("defaultImage").onload = function (){
console.log('Page has loaded');
};
Pen in question below. You can see the issue if you view it in debug view and do a hard refresh.
http://codepen.io/mhcreative/pen/GoxLPo?editors=0011
Any help would be much appreciated.
Thanks, All.
Here try this if you still want it natively.
$(document).ready(function(){
var img = new Image(); // Create new img element
img.addEventListener("load", function() {
TweenMax.to(["#backgroundLoad","#loadBoxes"],1,{alpha:0,delay:0.75});
}, false);
img.src = 'src/to/img'; // Set source path
$("#defaultImage").append(img); //append loaded image inside div
});

Get new image to only appear when loaded if source changed

I've been having a problem caused by the previous image staying on the screen until the next is loaded.
My program uses a flowchart where various images are needed for certain questions. I've been using the following code to change the source from one to another.
HTML:
<img class= 'right' id= 'imageBox' style= 'width: 20%; height: auto;' src= www.1stimage.com/>
javascript:
document.getElementById("imageBox").src = 'www.2ndimagesite.com';
If the computer has a slow connection, the first image could stay on the screen for up to 10 seconds before the next one shows up. How do I get it to not display anything until it's finished?
Thanks.
Preload the image and update the src after it's loaded:
var img = new Image();
var newsrc = 'www.2ndimagesite.com';
img.onload = function () {
document.getElementById("imageBox").src = newsrc;
};
img.src = newsrc;
You can change aproach a bit to achieve what you want.
You can preload images and after that just select what image to show. You can read more about this here: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
You can make start loading new image async and change current image to image like loading spinner or some image, which shows that something is loading at the moment (example: ) On onload handler you will rewrite this spinner to loaded image.
I wanted to write ~ same that #nedt wrote. Btw, I don't think that his code will help you. I think you will achieve same effect as you said in answer. Anyway, he was first and his answer was close, so I will just use his example.
document.getElementById("imageBox").src = "loading image link"; // load spinner
var img = new Image(); // load image asynchronously
var newsrc = 'www.2ndimagesite.com';
img.onload = function () { // onload handler
document.getElementById("imageBox").src = newsrc;
};
img.src = newsrc;
So, old image was loaded on page loaded. You did some action, for example pressed button. If you have low speed, loading spinner will be shown and after new image is loaded async, new image will be shown. If you have enought speed, new image will appear immediately.
Hope this will help you!
document.images[i].complete
will be true if picture[i] source is loaded.
you could preload all pictures an dont show it until the status change.

Replace img src but have loading graphic display while image is downloading

I have a page that swaps some fairly large images in and out. There are too many to preload when the page initially loads so that is not an option. So what I need to do is load them as they are requested by the user. Right now I'm using jQuery to replace the img's src. This works fine but the images I am loading can be around 500KB and it looks bad as they paint down the screen as they are downloading. What I'd like to do is pop a loading gif on the page when the image is in the process of loading then have the loading gif disappear once the image is loaded. I'm struggling to find a way to do that though. Here is the JS/jQuery code that I have that just replaces the src.
var product = "bowl";
var image = "dog.jpg"; //this is actually pulled from a data attribute, but its just hardcoded here for an example
$("#images img[data-product="+product+"]").attr("src", "/img/tablesetting/"+image);
I made a working jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
I recently needed to do the same thing. Basically I wrapped the image in a container div. within the container I've added a span element with my ajax loader gif embedded. this span has to be hidden initially but gets visible when an ajax request is made. The span gets removed when the image is fully loaded.
before ajax call
$('#your_image_container').find('span').show();
on success
$('#your_image').attr('src', 'your/image/url').load(function() {
$('#your_image_container').find('span').fadeOut();
});
I made a jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
Preload the image.
var product = "bowl";
var imageSrc = "dog.jpg";
var imgEl = $("#images img[data-product="+product+"]");
// show loading graphic only if it's needed
var timer = setTimeout(function(){
imgEl.attr("src", "/img/loading.gif");
},50);
// preload image
var img = new Image();
img.onload = function() {
clearTimeout(timer);
imgEl.attr("src",imageSrc);
}
img.src = imageSrc;
$img.attr("src", newImage);
if (!$img.get(0).complete) {
$img
.hide()
.after("<img src=throbber>")
.on("load", function () {
$(this).show().next().remove();
});
}

Gif loader while loading heavy png image

I load png image generated by server-side PHP script (chart) to the HTML IMG-element <img id="chart"> using following JS code:
$('#chart').attr('src', 'chart.php');
The PNG-image generation and downloading takes about 1 second, so I want to show gif loader while image is loading. How to implement this feature with JS?
For balance this is very simple to do in plain JS:
var preload = function(element, src) {
var img = new Image();
// Apply onload before applying src attribute to avoid IE prematurely firing
img.onload = function() {
// Replace #chart with image
element.parentNode.replaceChild(img, element);
};
img.src = src;
}
preload(document.getElementById('chart'), 'chart.php?_...');
$('#chart').attr('src', 'chart.php').load(function(){
//something
});
In case the browser caches it, you may way to add something to the query string to break that. Either way, you need to listen for the image's load event, which should be bound before setting its src (in case it's cached):
var target_url = 'chart.php?_=' + (new Date()).getTime();
// Show "loading"
$('#chart').on("load", function () {
// Hide "loading"
}).attr('src', target_url);
Reference:
http://api.jquery.com/load-event/
Note the caveats near the bottom of that reference, referring to the event when working with images:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache

Categories

Resources