I have a very simple code snippet to set a background image of an element once the image has loaded on a new image object.
var img = new Image();
var myelement = document.getElementById('myelement_id');
img.addEventListener('load', function(){
myelement.setAttribute('style', 'background-image: url(/public/images/myimage.jpg)');
});
img.src = '/public/images/myelement.jpg';
This question has already been asked a few times but answers have not been satisfying.
It's not the size of the image. The load event isn't fired no matter the size or format of the image.
The error event is not fired neither. Some people suggested that the error event will be fired instead of the load event on IOS.
It's not the browser. It's IOS. The behaviour is the same on Safari or Chrome on IOS.
It's not observable with BrowserStack. The image loads fine on BrowserStack yet a physical device is incapable of firing the load event.
I do assign the function first and thereafter set src to trigger the load event.
This seems to be working for me. But I am not sure whether changing the add event listener to the .load event made the difference.
function imgLoad(_imgDOM, _imgID){
_imgDOM.setAttribute('style', 'background-image: url(/public/images/load/' + _imgID + '.jpg)');
}
var imgLoadArray = document.querySelectorAll('.img__load');
for (var i = 0; i < imgLoadArray.length; i++) {
var imgDOM = imgLoadArray[i];
var imgID = imgDOM.getAttribute('id');
var img = new Image();
img.onload = imgLoad(imgDOM, imgID);
img.src = '/public/images/load/' + imgID + '.jpg';
}
Related
I'm trying to trigger function on "onload" event of Image() (HTMLImageElement) on Android with Ionic 3. It works with iOS but unfortunately doesn't work with Android.
How can I trigger onload function on Android? I do not use it with <img> or other tag, so I cannot fire it with <img (load)="functionHere()">.
(I have seen some of the other "onload" questions on Stack Overflow, this is about a specific situation with Android/Ionic 3).
Here is my example code:
this.backgroundImageSource = new Image();
this.backgroundImageSource.src = this.image;
this.backgroundImageSource.onload = function() {
// THIS PART DOESNT FIRE ON ANDROID
console.log("ONLOAD TRIGGERED");
}
If the example code is used exactly as shown, then the issue could be with onload event handler being defined after the event could happen. You should define the event handler function before the event could occur.
So onload must be handled before src attribute is set. Although, I'm not sure if the JS engine fixes this in any of its optimization steps.
this.backgroundImageSource = new Image();
//This has to be done before setting src
this.backgroundImageSource.onload = function() {
console.log("ONLOAD TRIGGERED");
}
this.backgroundImageSource.src = this.image;
I had the same problem.
I discovered that the base64 did not include a header/descriptor and so for that reason it was not firing.
I fixed this by appending a header in cases where one did not exist:
if (!base64Data.includes(',')) {
// Detect if base64 image is missing header/descriptor
console.log("Prepending descriptor to Base64 image string")
base64Data = `data:image/jpeg;base64,${base64Data}`;
}
(The comma is used to separate the header from the body).
I am loading an image from the file system and then I want to resize the image. it works fine in all browsers except for IE (11). Problem is that the image is loaded, but the width and height are 0.
I am out of options so I am posting this question here.
This is the code
function getAsImage(readFile, chatboxtitle) {
var reader = new FileReader();
reader.readAsDataURL(readFile);
reader.onload = addImg;
}
function addImg(imgsrc) {
var img = document.createElement('img');
img.setAttribute("src", imgsrc.target.result);
console.log(img);
console.log(img.width + " "+img.height);
... a lot of cool stuff happens here but it doesn't work because width is 0
}
OK, so the console prints the image which is like
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABAAAAAH0CAYAAAHUIW ... and much more.. >
So the image IS there. All browsers work fine except IE.
I tried to play with setting some IMG properties like style, width but none work.
Note, I am not a hardcore JavaScript developer. Maybe I am missing something. Is the DOM element not found?
UPDATE
I tried the answer below yesterday and it was working. But I tried the solution today and it is not working anymore. Try this fiddle .
It is not working in IE11 on Windows7 but it is on IE11 on Windows8.
Weird IE behaviour. It turns out that you need to set src using
img.src = src_goes_here
Not via setAttribute
(function(doc){
doc.getElementById('file').addEventListener('change', readFile);
function readFile(ev) {
var file = this.files[0],
reader;
if(file) {
reader = new FileReader();
reader.onload = getSize
reader.readAsDataURL(file);
}
}
function getSize(ev) {
var img = doc.createElement('IMG');
img.src = this.result; //wors in IE11
//img.setAttribute('src', this.result); //doesn't work
console.log(img.width, img.height);
}
}(document))
Demo.
UPD: Some additional research shows that in order to make IE to calculate image sizes when you set src using img.setAttribute you need to actually attach the image to the document. For example
document.body.appendChild(img);
Another Demo.
I have a function where I get the img src value as the parameter, what I want to do is check to see if that image loads with a 200 ok or 404/some other error. If it gets a 200 ok, then I want to inject an img tag with that src into the DOM(I reason that during checking,it also gets loaded into the browser cache and injecting that img tag into the DOM loads it from the cache ). I tried with a simple snippet of code as follows :
function checkImage(src)
{
var img = new Image(),
tag = '<img src="'+src+'" />',
alt = '<span>sorry,image broken</span>';
img.onload = function(){
$('.some-container').html(tag);
};
img.onerror = function(){
$('.some-container').html(alt);
};
img.src = src;
}
It worked fine in chrome, but went havok in firefox and ie(both of them are firing only the error event no matter whether the image loaded fine or broke). Instead of using onload and onerror, I tried it using jquery like :
$(img).load(...).error(...).attr('src',url);
$(img).on('load',...).on('error',...).attr('src',url);
$('<img />').load(...).error(...).attr('src',url);
$('<img />').on('load',...).on('error',...).attr('src',url);
and even tried the jquery.imagesLoaded plugin by desandro(https://github.com/desandro/imagesloaded) like :
$(img).imagesLoaded().done(...).fail(...);
$(img).imagesLoaded().progress(function(instance,image){
image.isLoaded?alert('loaded'):alert('broken');
});
$('<img />').imagesLoaded().done(...).fail(...).attr('src',url);
$('<img />').imagesLoaded().progress(function(instance,image){
image.isLoaded?alert('loaded'):alert('broken');
});
I also tried the solutions from :
jQuery callback on image load (even when the image is cached)
https://groups.google.com/forum/#!topic/jquery-dev/7uarey2lDh8
but as it turns out, works in chrome, but not in FF or IE, is there any solution where I can check for an image which is present in memory but not in the "DOM" ? Thanks in advance.
You have to check for image onload after setting a source to it.
var img = new Image();
//set source to the image
img.src = "set/image/source/path"
img.onload = function(){
//if image load is successful
//create an jQuery object out of this image
var jQimage = $(this);
$('.myContainer').html(jQimage);
}
Also note that jQuery load function cannot guarantee you a cross browser check for image loading as mentioned in jQuery docs
So, the best approach is to check onload with native javascript and create an jQuery object if necessary to make use of jQuery methods.
Have a look at what w3schools has to say about the Image() javascript object.
http://www.w3schools.com/jsref/dom_obj_image.asp
onabort - Loading of an image is interrupted, W3C YES
onerror - An error occurs when loading an image, W3C YES
onload - An image is finished loading, W3C YES
also the complete property of the Image() object, determines if the browser is finished loading an image, Unfortunately this particular property is not W3c
hope that helps a little
PS: After having a little Google search I found this Q/A from Stack overflow.
Cross-browser image onload event handling
I can't seem to find a definitive answer to this one...
Assume I have a JavaScript reference to an image on the page and I bind a load event handler to that element. For example, something like this:
HTML
<img id="myImage" src="http://example.com/image.jpg" />
JavaScript
var $myImage = $('#myImage');
$myImage.load(function() {
alert('Image loaded!')
});
Now, if I do this:
var imageElem = $myImage[0];
imageElem.src = imageElem.src; // Re-assign the image source path
...will the load event handler fire even if the image has already been loaded from the server? It seems to do in Firefox, but is it safe to rely on this behaviour?
(The reason I ask is I've seen this used in a jQuery plugin to check when all images have been loaded. If the image is loaded before the load event handler is bound, then it won't fire, unless it's re-triggered using the method above.)
Setting img.src should trigger load, with some caveats. According to jQuery's own documentation regarding the .load event,
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
checked this in Chrome inspector:
> img = document.createElement('img')
<img>
> img.addEventListener('load', function(e) {console.log('loaded');});
undefined
> img.src = 'http://placekitten.com/200/300';
"http://placekitten.com/200/300"
loaded
> img.src = 'http://placekitten.com/200/300';
"http://placekitten.com/200/300"
> img.src = 'http://placekitten.com/200/30';
"http://placekitten.com/200/30"
loaded
> img.src = 'http://placekitten.com/200/300';
"http://placekitten.com/200/300"
loaded
> img.src = 'http://placekitten.com/200/300';
"http://placekitten.com/200/300"
So to answer with regards to Chrome - no, not unless you set the src to something else first.
I had this problem too and found a simple solution.
You can fire the loaded event multiple times by replacing the source attribute. Even if the value equals the existing source. You just have to add an different parameter, which is ignored by the server.
Take a look at this example:
var source = "http://example.com/image.jpg";
var imageElement = document.createElement('img');
imageElement.src = source + "?ignorethis=" + new Date().getTime(); // loaded
imageElement.src = source + "?ignorethis=" + new Date().getTime(); // loaded again
I know, it's a bit dirty, but works cross-browser.
I am developing an app that embeds users' Facebook profile picture(http://graph.facebook.com/(fb id)/picture) inside an img tag. And it works...for the most part. However I will occasionally get 400 errors when I request the profile picture(see this)
Is there any way I can detect these 400 errors with Javascript/JQuery? Right now they are being displayed as a broken image....
This is pretty simple using the onerror event.
We can simply create a new image in JavaScript and attach two events to it - onload and onerror. Then setting the image src will make the browser download the image, firing the onload event if it is a true image, or onerror if not.
var img = new Image();
// This URL will return an image an fire `onload`
img.src = 'http://placekitten.com/300/300';
// Replace the line above with this one to load a fake/unavailable image, which will fire the `onerror` event.
// img.src = 'http://mybrokenurl';
img.onload = function() {
document.body.appendChild(img);
}
img.onerror = function() {
alert('Error loading image');
}
Demo: http://jsfiddle.net/amustill/vSJ4F/