Javascript load Eventlistener - javascript

I just wanted to ask how do you ensure that element details (e.g position in viewport, getBoundingClientRect) are correct when loading your page for the first time. Currently I have a problem with a normal div-element. It is displayed right after an image which i get with a fetch statement. I used the load-event on window and after the Page is loaded I get the information of the position of the div-element. Unfortunately the load-fires before the Image is loaded and that means the position details are wrong.
How and when do you use the load Event? And what Else can i do to ensure i receive the right position details.
Html
<div class="wrapperImg"></div> <div class="position"></div>
Js
window.addEventListener("load",()=>{console.log(document.querySelector(".position").getBoundingClientRect());}
Many thanks
Regards
Kat

You'd need to call the getBoundingClientRect() after the image has loaded, which means when your fetch call has resolved (as it is executed asynchronously).
To keep in mind: The load event does not include asnyc fetched resources (as those are handled dynamically). For more info on the load event see the documentation.

'load' event listener can also be applied on images like this:
var img = new Image();
img.src = "img.jpg";
img.onload = function () {
alert("image is loaded");
}
Also you can get getBoundingClientRect() properties after the fetch:
fetch('image.png').then(i => {
//get size
})

Related

Detect inline image loading

I know there are many ways to detect if images have been loaded the traditional way (i.e. <img src="bar.jpg"/>, but is there a way to detect when images are completely loaded inline (as in, <div class="foo" style="background-image: url(bar.jpg)">)?
I am uploading images via FilePicker and the image is then set as the background image to the parent div.
The window load event signifies that all images in the page have been loaded.
From MDN:
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images and sub-frames have finished loading.
This occurs during the initial load of the page for the resources specified in the HTML of the page.
If you are dynamically setting an image to be a background image, there is no event for when that background image has been loaded. If you wanted to know when that image was loaded, you could load it yourself in an image object and watch the onload handler for that image object and then when loaded, you could set it as the background image. It would be cached at that point so the background would show immediately.
function setBackgroundNotify(imgURL, targetObj, callback) {
var img = new Image();
img.onload = function() {
targetObj.style.backgroundImage = "url(" + imgURL + ")";
callback();
};
img.src = imgURL;
}
#jfriend00 is correct. That answer has the advantage of having no dependence on other libraries.
However, if you are already using jQuery (as the tag on your question suggests), you can achieve the same thing with .on("load",...).
http://api.jquery.com/load-event/
Note, the .load(...) shortcut has been deprecated, so use .on("load", ...) instead. This has at least one advantage over window.onload. It allows queueing of multiple event handlers, whereas an inadvertent reassignment of window.onload will blow your handler away. Furthermore, in the off chance there are any browser incompatibilities with window.onload, the jQuery solution will likely automagically handle them.
You can (more or less) prove to yourself it is working with a little profiling:
$(document).ready(function() {
console.log("Document ready at " + Date.now());
});
$(window).on("load", function() {
console.log("First window on load at " + Date.now());
});
$(window).on("load", function() {
console.log("Second window on load at " + Date.now());
});
Assuming you've got some div's doing some really expensive background image loading, you should see a noticeable lag in time between document ready and the first window on load.

$.ajax.load() triggers callback before images are loaded

Why does ajax load() triggers callback before all images are fully loaded.
$(element).load("url #id", function()
{
$(this).fadeIn();
})
When I load data, element fades in and I see how images are drawn slowly on my screen... is it that image is loaded but computer is slow?
What should I do to show content after it's fully loaded?
$(element).load will load content into your element, but then you can find all images and attach a load callback on them to determine when all images have been loaded. However, this is not very reliable since the load event on images might never fire for various reasons. In some browsers, the load event will be synchronous when the image is cached, so it will fire before we even attached an event handler on the image. For that reason, if images are not loaded after 5 seconds, we show the element anyway.
$(element).load("url #id", function () {
var $self = $(this),
$images = $self.find('img'),
imgCount = $images.length,
loadedCount = 0;
$images.on('load', function () {
if (++loadedCount === imgCount) {
$self.fadeIn();
$(this).off('load');
}
});
setTimeout(function () {
if (loadedCount !== imgCount) {
$self.fadeIn();
$images.off('load');
}
}, 5000);
});
From the jQuery documentation:
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load()
shortcut is to execute a function when an image (or collection of
images) have completely loaded. There are several known caveats with
this that should be noted. These are:
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
In the same documentation they offer a soultion to display graphics when they are loaded.
You can chech for the height property to be what it needs to be before displaying the image, since it will change size only when it has really been loaded (only if you did not specify it in the css though).

Placeholder while an image is loading with Ember.js [duplicate]

I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.
What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this.
I've been doing this via JavaScript, which works so far, using the following code
document.getElementById('chart').src = '/charts/10.png';
The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond.
What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it.
I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image.
A good suggestion I've had is to use the following
<img src="/charts/10.png" lowsrc="/spinner.gif"/>
Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed.
Any other ideas?
I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback.
function PreloadImage(imgSrc, callback){
var objImagePreloader = new Image();
objImagePreloader.src = imgSrc;
if(objImagePreloader.complete){
callback();
objImagePreloader.onload=function(){};
}
else{
objImagePreloader.onload = function() {
callback();
// clear onLoad, IE behaves irratically with animated gifs otherwise
objImagePreloader.onload=function(){};
}
}
}
You could show a static image that gives the optical illusion of a spinny-wheel, like these.
Using the load() method of jQuery, it is easily possible to do something as soon as an image is loaded:
$('img.example').load(function() {
$('#spinner').fadeOut();
});
See: http://api.jquery.com/load-event/
Use the power of the setTimeout() function (More info) - this allows you set a timer to trigger a function call in the future, and calling it won't block execution of the current / other functions (async.).
Position a div containing the spinner above the chart image, with it's css display attribute set to none:
<div> <img src="spinner.gif" id="spinnerImg" style="display: none;" /></div>
The nbsp stop the div collapsing when the spinner is hidden. Without it, when you toggle display of the spinner, your layout will "twitch"
function chartOnClick() {
//How long to show the spinner for in ms (eg 3 seconds)
var spinnerShowTime = 3000
//Show the spinner
document.getElementById('spinnerImg').style.display = "";
//Change the chart src
document.getElementById('chart').src = '/charts/10.png';
//Set the timeout on the spinner
setTimeout("hideSpinner()", spinnerShowTime);
}
function hideSpinner() {
document.getElementById('spinnerImg').style.display = "none";
}
Use CSS to set the loading animation as a centered background-image for the image's container.
Then when loading the new large image, first set the src to a preloaded transparent 1 pixel gif.
e.g.
document.getElementById('mainimg').src = '/images/1pix.gif';
document.getElementById('mainimg').src = '/images/large_image.jpg';
While the large_image.jpg is loading, the background will show through the 1pix transparent gif.
Building on Ed's answer, I would prefer to see something like:
function PreLoadImage( srcURL, callback, errorCallback ) {
var thePic = new Image();
thePic.onload = function() {
callback();
thePic.onload = function(){};
}
thePic.onerror = function() {
errorCallback();
}
thePic.src = srcURL;
}
Your callback can display the image in its proper place and dispose/hide of a spinner, and the errorCallback prevents your page from "beachballing". All event driven, no timers or polling, plus you don't have to add the additional if statements to check if the image completed loading while you where setting up your events - since they're set up beforehand they'll trigger regardless of how quickly the images loads.
Some time ago I have written a jQuery plugin which handles displaying a spinner automatically http://denysonique.github.com/imgPreload/
Looking in to its source code should help you with detecting when to display the spinner and with displaying it in the centre of the loaded image.
I like #duddle's jquery method but find that load() isn't always called (such as when the image is retrieved from cache in IE). I use this version instead:
$('img.example').one('load', function() {
$('#spinner').remove();
}).each(function() {
if(this.complete) {
$(this).trigger('load');
}
});
This calls load at most one time and immediately if it's already completed loading.
put the spinner in a div the same size as the chart, you know the height and width so you can use relative positioning to center it correctly.
Aside from the lowsrc option, I've also used a background-image on the img's container.
Be aware that the callback function is also called if the image src doesn't exist (http 404 error). To avoid this you can check the width of the image, like:
if(this.width == 0) return false;
#iAn's solution looks good to me. The only thing I'd change is instead of using setTimeout, I'd try and hook into the images 'Load' event. This way, if the image takes longer than 3 seconds to download, you'll still get the spinner.
On the other hand, if it takes less time to download, you'll get the spinner for less than 3 seconds.
I would add some random digits to avoid the browser cache.

HTML / Javascript wait for graphics to be drawn

I've heard about the onload function which is called after the element is fully loaded.
In the case of graphics or images, does that mean it will wait until the image is displayed in the browser?
<body onload="foo()">...
<img onload="bar();"....
If not, is there a way to get the event when all graphics are drawn and images are displayed on a page?
In my case it´s only one 1600*1200 jpeg image and i draw on it. But the image has to be displayed before i start drawing, even with the onload event i see the drawed lines before the image appear.
Yes body onload will wait until all images (and other content) are loaded/displayed in the browser. The img onload will wait until that specific image has loaded/is displayed
Images have a complete property that's true when they are loaded.
e.g. would test if everything has loaded:
var allImagesLoaded = true;
$("IMG").each(function(){ allImagesLoaded &= $(this).attr("complete"); });
if(allImagesLoaded){ alert("Done!");}
Images raise a load event once they've finished loading
why dont you keep a counter for your images that will decrement by one on each image load.
check if it equal to 0 then call some another function.
in this way you can do the thing you want to when all images are loaded
$(function() {
$('img').one('load',function() {
// fire when image loads decrement the counter
if counter ==0
fireanotherfunction()
});
});
by above code u can attain your purpose
When reading the jQuery ready API documentation here:
While JavaScript provides the load event for executing code when a
page is rendered, this event does not get triggered until all assets
such as images have been completely received.
So onload is launched after everything has been loaded (and displayed).
See the window.load event:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
This is exact what you want, I believe.
JQuery's $(document).ready is not what you want:
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event [instead of the ready event].
If you're using plain JS, window.load is what you want.
If you are using jQuery, you'll want $(document).load.
try jquery ready function
$(document).ready(function(){
bar();
});
I'm not sure if it works, but it's a try :D
I have the same problem developing a web view for an Android app. The load events (both for window and image element) as well as the complete state of the image element fire too early. My (svg) image has not yet finished drawing and thus calculations on the size go wrong.
The only workaround that I have found is a very short timer (1ms or maybe 10ms). That works for me because I have only one such image to consider. And since I start this timer when the image data has already loaded, this short lapse should be long enough for the device to paint the image.
window.addEventListener('load', function() {
var img = document.getElementById('logo');
window.setTimeout(function(){
var imgRatio = img.naturalWidth / img.naturalHeight;
var renderedWidth = parseInt(window.getComputedStyle(img).width.match(/(\d+)px/));
console.log(renderedWidth, img.complete);
if (renderedWidth < img.naturalWidth) {
img.style.height = (renderedWidth / imgRatio) + 'px';
}
}, 1);
}
Instead of the window load event, the image's load event should also work. But I found it safer to wait for everything, because other elements might affect the drawing of my image.

Image width traces zero with onload when cached

I'm building a Javascript lightbox and I'm trying to adjust the size once the image has loaded. I'm using the code below, which works fine - it outputs the correct width once loaded.
My problem:
When I refresh, it will load the image instantly from the cache, and it seems to bypass the load. I get an instant zero for the width. Why does this happen?
My code:
var oImage = new Image();
oImage.src = 'http://mydomain.com/image.png';
container.html(oImage);
oImage.onload = function(){
alert(this.width);
}
** Update **
#Alex: This is the code I've tried with your plugin, I assume I'm probably doing something wrong. I'd be eager to get this working because your plugin looks quite good.
container.waitForImages(function() {
var cWidth = $(this).width();
alert("width: "+cWidth); // returns 0 - works first time but not cached
});
// Adding the image to the container for preload
container.html('<img src="mygraphic.png" />');
You need to do a few things...
Check the complete property of the img element.
Attach the load event before setting the src property.
Also, I found creating a new Image and assigning the src there is the best way to determine if the image has loaded or not.
You may want to switch the .html() and the .onload() calls.
If the image is loading from cache, I'm imagining that the .html() call completes before the script has had a chance to attach a function handler to the image's onload event. Therefore, effectively bypassing the load event itself (as the image has already loaded).
If it's still downloading the image (i.e. not cached), there will be more than enough time to call the .onload attach before the image completely finishes rendering.
While you're at it, you may want to do this the jQuery way, just so you're attaching events more similarly to DOM2 than DOM0.
var image = $('<img/>', {
src : 'http://mydomain.com/image.png'
}).load(function () {
alert(this.width);
})
// maybe clear container before if you want
.appendTo(container);
If we're going to have to set the src after the onload, we might as well do this instead:
var image = $('<img/>')
.load(function () {
alert(this.width);
})
.attr('src','http://mydomain.com/image.png')
.appendTo(container)
;
Hopefully that works cleanly.
This answer JavaScript: Know when an image is fully loaded suggests that you should set onload before setting src

Categories

Resources