javascript img onload() - javascript

I am using <img> onload function to trigger the resize action on the image that has been loaded. But I found if in one webpage there is two or more <img>s with the same "src", which means the image is the same, the latter <img>'s onload() function will not be invoked. How to make sure that all the <img>s are properly resized even when there are some <img>s with the same src?
Thanks.

This is happening because your browser is actually caching the first image. So when you attempt to load the same "src" again, it's cached locally and never actually fires an onload. To get it to load at all times, you could append on a unique value to the query string.

Instead of using a separate onload handler for each <img/>, why not just use a single onload event for the window? This event fires after everything (like all the images) have loaded, so you could just process each image in that single handler. Something like:
function processAllImages()
{
var imgElts = document.getElementsByTagName('img');
for (var i=0; i<imgElts.length; i++)
{
processImage(imgElts[i]); // TODO write this function
}
}
window.onload = processAllImages;

I asked similar question before. Check this out: Javascript/jQuery: How to detect img is fully downloaded or not?
In short, you can use 'complete' property of img tag.
check it before you bind load event.

Related

Can´t attach eventlistener to onload event of <img>-Tag

I am wondering why I can´t attach an eventlistener to the onload event of an html image.
<img id="imageID" onload="doSomething();"> works perfectly,
but if I want to add a listener like
document.getElementById('imageID').addEventListener('onload', function(e) {
doSomething();
});
or with jQuery
$("imageID").on("onload", function(){
doSomething();
});
the event is not being catched. If I listen for a simple "click"-Event it works, but not with the "onload"-Event.
Can anybody tell my the reason for this behaviour?
Don't include "on" in the event name.
// no "on"------------v
document.getElementById('imageID').addEventListener('load', function(e) {
// no "on"----v
$("#imageID").on("load", function(){
// ^----need "#"
There are two problems here.
You don't put "on" in the event name, as I Hate Lazy said.
If you're trying to hook the load event on an image that's already on the page, you'll have a race condition and sometimes won't see the event, because it can be "loaded" the instant that it is put on the page (if the relevant image is in cache). You have to hook load before the image has a src attribute, which typically means adding the image dynamically. Your DOM0 handler (the onload="doSomething()") works because it's already attached when the image is added to the document, but anything looking the image up on the page later (getElementById or jQuery) may miss it.

how to handle onLoad Event on img tag and others

how to handle onLoad Event on img tag?
example:
$ ('img'). onload (function (e) {
alert ('image loaded' + $ (this), attr ('src'));
})
is like the imageLoader
and others tags like script, link, etc...
jQuery callback on image load (even when the image is cached)
$("img").one('load', function() {
// do stuff
}).each(function() {
if(this.complete) $(this).load();
});
Seems to work for me, and should fix the caveat with caching.
There's an example of how to do this right on the jQuery doc page for .load().
HTML:
<img src="book.png" alt="Book" id="book" />
Javascript:
$('#book').load(function() {
// Handler for .load() called.
});
And, there are a bunch of caveats to watch out for listed on that jQuery page too.
With images, if you want to assure that the load handler gets called, the load handler has to be set before the image can possibly be loaded. If you're constructing the image in code, that means you have to set the load handler before you set the .src attribute. That's because, in some browsers, if the image is in the memory/disk cache, it will load immediately when you assign .src and if you then subsequently set the .load() handler, you will be too late (the image will already be loaded) and the .load() handler will never be called.
I don't know how to guarantee that a jQuery-based .load() always gets called for an image that's in your page HTML because you can't assign the event handler until the object exists, but once the object it exits, it might already be loaded. You can use non-jQuery setting of an onload=xxx in the actual HTML though that is an older style of coding. Of course, you can always hook window.onload to know when all page images (and other resources) have been loaded.
jQuery has a load method, not onload. And your code should probably be:
$ ('img').load(function () {
alert('image loaded ' + this.src);
})

How to use jQuery live() for img onload event?

I want to run some code when an image is loaded. Also, I'd like to do it unobtrusively (not inline). More specifically, I want to use jQuery's live() function so it will happen for any dynamically loaded images.
I've tried:
<img class="content_image" alt="" src="..." />
<script>
$('.content_image').live('load', function() {
alert('loaded!');
});
</script>
In addition to load, I've tried onload, and onLoad. When I replace with 'click' all works as expected so I know it's not some interfering bug.
I haven't been able to find a list of available event types for the live() function, so for all I know, it may not be possible.
(It would be load, not onload or onLoad.)
load doesn't bubble (according to the img entry in the HTML5 spec, it's a "simple event", which don't bubble), so you can't use it with live or delegate, which rely on the event bubbling from an element to its ancestor element(s).
You'll have to hook it on the individual img elements (and do so before you set their src, since otherwise you can miss it; and always remember to watch for error as well). (Yes, you really can miss it: The browser is not single-threaded, just the JavaScript main thread. If you set src and the image is in cache or becomes available soon enough, the browser can fire the event. The way events are fired is that the browser looks to see what handlers are registered as of when the event is fired, and queues those to be called when the JavaScript main thread yields back to the browser. If there are no handlers registered, they aren't queued, and you never get the callback.)
it's a little bit dirty, but it works :
<script type="text/javascript">
var loop = setInterval(function() {
// the img to watch
var $img = $("img.hi");
if( !!$img.length && $img[0].complete ) {
// clear the timer
clearInterval(loop);
alert("loaded !");
}
}, 30);
</script>
<img class="hi" src="http://www.google.fr/images/nav_logo72.png" />
Finaly I stumbled upon this jQuery plugin :
https://github.com/desandro/imagesloaded

assign event to div when it has loaded fully

Can I assign an event to a div to fire when all elements of the containing div have loaded fully? eg. if the div contains an image, fire an event on the div when the image has loaded fully. I am using jquery.
Not sure how you're dynamically adding your content, but this example should illustrate how it could work.
It is using .append() to simulate your dynamically loaded content. Then after the append, it uses .find() to find the images, and .load() to attach a load handler to them.
Finally, it returns the length property of the images. Then in the load handler, as the images finish loading, the length is decremented. Once it gets to 0, all the images are loaded, and the code inside the if() runs.
Example: http://jsfiddle.net/ehwyF/
var len = $('#mydiv').append('<img src = "http://dummyimage.com/150x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/160x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/170x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/180x90/f00/fff.png&text=my+image" />')
.find('img')
.load(function() {
if( --len === 0) {
alert('all are loaded');
}
}).length;
This way, the code runs based only on the images in #mydiv.
If there are any images in there that were not dynamic, and therefore shouldn't get the .load() event, you should be able to add a .not() filter to exclude ones the complete property is true.
Place this after the .find() and before the .load().
.not(function(){return this.complete})
If it's just one image you're wanting to wait for you can load the image with ajax and then trigger the event in the ajax callback.
It's hard to check it for just one div, but may I suggest using $(window).load() to check if all the images have loaded?
UPDATE:
If you using ajax then use the callback to see when the json has loaded, and then attach $("div#id img").load() to see when all the images have loaded. Only problem with this is that I have noticed when the image is cached, the loader does not get triggered. :(
To add to Shadow Wizard's idea, you could try the following code:
var totalImages = $(".yourImageClass").length;
var loadedImages = 0;
$(".yourImageClass").bind("onload", function() {
loadedImages++;
if (loadedImages == totalImages) {
//all images have loaded - bind event to DIV now
$("#yourDiv").bind(eventType, function() {
//code to attach
});
}
});
Catch the onload event of all images in the div, in there raise some global counter by 1. If that counter is equal to the amount of images in the div... all images finished loading.
Should be simple using jQuery.
This will work only for images though, other elements don't have onload event.

Javascript/jQuery HasLoaded or equivalent?

I know in jquery it is possible to call the javascript/jquery onload()/load() functions on, for example an image (<img>).
However, if in jquery if i use .html(htmlString) to insert an image after the dom has loaded, how can i add a listener to handle the images onload event? Is there a property I can check to see various images and if they have loaded?
After appending your html, you can bind the load event to the contained images:
$("#foo").html(htmlString).find("img").one("load", function() {
...
}).each(function() {
// image has been cached, so load event won't fire unless we explicitly call it
if(this.complete) $(this).trigger("load");
});
Check the complete property of the image(s)

Categories