In the console I have 180 failed to load resources, I need to get a list of these resources so that I can send a report to the webmaster with the images URLs. How can this be done?
You can easily track images that fail to load, as long as you set up an event listener before the image starts to load. Like this:
img.addEventListener('error', function() {
//report failed image
}, false);
If all of your images are loaded in <img> tags that are in the html, you can set up an error event for all of them in a script. Just make sure the script that sets this up is placed after the img tags, but do not run the setup in a page load event or DOMContentLoaded because you may have missed some error events, and it will be too late.
See this example:
http://jsbin.com/ekiram/2/edit
If you want, you can set up a MutationObserver event to watch for any new <img> elements added dynamically and set up an error event there. But it won't work in all browsers.
You can check whether an image has loaded by looking at the naturalWidth property. If it's 0, it hasn't loaded. But there's no way to know whether the image has actually failed to load or is just taking a really long time, like if there's a slow network connection. I suppose you could use this if you have another way to know if the page and all images are really done loading, like after a page load event or if you're willing to set a very long timeout.
If you can add a script to the page, you can bind a handler to the error event and track all failures:
$(function(){
var errorImages = [];
$('img').on('error', function(){
errorImages.push(this.src);
});
$(window).on('load', function(){
alert(errorImages);
});
});
Working example: http://jsbin.com/iboyik/3
If you want to get all failed images on a page that is already loaded, that is a little trickier. I was able to do that by reloading all images:
(function(){
var errorImages = [];
$('img')
.on('error', function(){
errorImages.push(this.src);
})
.prop('src', function(i, src){return src;});
// wait for all images to fail (bit of a hack)
setTimeout(function(){alert(errorImages);}, 1000);
})();
Working example: http://jsbin.com/iboyik/2
Related
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).
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.
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
I have a web page where lots of images called from server using image
scr attribute.
I have created a function like which is triggered by td click.
function GoToStep(stepNo) {
var imgSrc = $("#h1" + stepNo).val();
$(".img_vertical").css("background-image", "url(" + imgSrc + ")");
}
Now the problem is this. For slower connections the images come after some
moment.
Can I pre load images to avoid waiting time when user clicks
td?
I have seen some jquery function to pre load images.
Kindly give some idea how can I achieve it.
Pre-loading an image is equivalent to loading an image but never displaying it. So, you can easily do it like this:
<img src="image.png" alt="" style="display:none;"/>
Now this image will be loaded as soon as the html starts rendering. Whenever you need to use this image as a display or background, just set the address to image.png and it will automatically be fetched from browser's cache.
This can be done using some javascript functions. Quoting from another question.
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
Explanation of how javascript preloaders work (different question)
[...] The way it works is simply by creating a new Image object and setting
the src of it, the browser is going to go grab the image. We're not
adding this particular image to the browser, but when the time comes
to show the image in the page via whatever method we have setup, the
browser will already have it in its cache and will not go fetch it
again. [...]
So in your case, you should use something like
$(function() {
// Do stuff when DOM is ready
preload([
'img/bg1.jpg',
'img/bg2.jpg',
'img/bg3.jpg'
]);
});
I have a gallery I quickly coded up for a small site, and under Firefox 3 and Safari 3 works fine. But when I test on my old best friend IE7, it seems to not fire the imageVar.onload = function() { // code here }.. which I want to use to stop the load effect and load the image.
Please bear in mind...
I know the thumbnails are just scaled down version of the larger images. When the images are finalised by the client I am going to create proper thumbnails.
This is my first attempt to try and get out of procedural JavaScript for the most part.. so please go easy and kindly let me know where my code sucks!
For successful use of Image.onload, you must register the event handler method before the src attribute is set.
Related Information in this Question:
Javascript callback for Image Loading
Cross browser event support is not so straightforward due to implementation differences. Since you are using jQuery at your site, you are better off using its events methods to normalize browser support:
instead of:
window.load = function(){
//actions to be performed on window load
}
imageViewer.image.onload = function(){
//actions to be performed on image load
}
Do:
$(window).load(function(){
//actions to be performed on window load
});
$(imageViewer.image).load(function(){
//actions to be performed on image load
});
Just to add to the suggestion by Eran to use the jQuery's built in event handlers you can run code when the document is loaded and the DOM is created but before the images are downloaded with:
$(document).ready(function(){
//your code
});