Is this an efficient way to display an image using jQuery - javascript

This code works, but is it an efficient way to go about displaying an image once it has been loaded?
LightBoxNamespace.SetupLightBox = function(path, lightBox) {
// Create a new image.
var image = new Image();
// The onload function must come before we set the image's src, see link for explanation.
// http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called.
// Anonymous function set to onload event, to make sure we only proceed if the image has been loaded.
image.onload = function () {
if ($('#image').length) {
$('#image').attr('src', path); // If the element already exists, change the src to our loaded image.
}
else {
$('<img id="image" alt="">').attr('src', path).insertAfter('#close'); // If the element does not exist, insert the full image html into the lightbox.
}
LightBoxNamespace.CentreBoxInViewport(lightBox);
LightBoxNamespace.ShowOverlay(lightBox);
};
// Set the src, and show the image.
image.src = path;
};

var img = $('<img>');
img.load(function(){alert("image loaded!")});
img.attr('src', "url");
if (!! img) img.appendTo('#close');
http://jsfiddle.net/W57QR/4/

"The jQuery way":
var $img = $('<img/>').prop({ src: path });
$img.load(function() {
console.log('image loaded correctly');
$(this).insertAfter('#close');
}).error(function() {
console.log('error loading image');
});

Related

Deferred (lazy) loading of background images?

I'm using a simple script to cause a deferred loading of all images on a page; the path for the image sources is contained in a data-src attribute and then put into the actual srcattribute of the img tag(s). Pretty much how most (?) implementations of the lazy loading method work.
Here's the script:
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
img.setAttribute('src', img.getAttribute('data-src'));
img.onload = function() {
img.removeAttribute('data-src');
};
});
I would like to use the same script for deferred loading of background images as well. How do I have to change it so that the data-src attribute ends up in the url-value of a div's background-image-property?
I tried the following with no results, because the script doesn't recognise background-image as a property:
[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
div.setAttribute('background-image', div.getAttribute('data-src'));
div.onload = function() {
div.removeAttribute('data-src');
};
});
Problem may be with the background image as an attribute. Have you tried setting the style with the background image?
[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
div.setAttribute("style","background-image: url(" + div.getAttribute('data-src') + ");");
div.onload = function() {
div.removeAttribute('data-src');
};
});
[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
div.style.backgroundImage="url('" + div.getAttribute('data-src') + "')";
div.onload = function() {
div.removeAttribute('data-src');
};
});
Try this

Image source not changing with JavaScript

Please answer this question, as I am struggling a lot with it.
I am trying to change image source on mouse over. I am able to do it, but image is not displaying on page.
I am trying to change image source to cross domain URL. I can see that in DOM image source is changing but on page its not.
I have tried all solutions mentioned in LINK, but none of them is working.
Please let me solution to problem.
NOTE:
I can see in network tab image is taking some time to download (about 1 sec).
It is an intermediate issue, sometime image is loading and sometimes its not
CODE:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function()
{
document.getElementsByTagName('img')[0].setAttribute('src', 'url/of/the/image');
});
have you tried loading images before everything else?
function initImages(){
var imC = 0;
var imN = 0;
for ( var i in Images ) imN++;
for(var i in Images){
var t=Images[i];
Images[i]=new Image();
Images[i].src=t;
Images[i].onload = function (){
imC++;
if(imC == imN){
console.log("Load Completed");
preloaded = 1;
}
}
}
}
and
var Images = {
one image: "path/to/1.png",
....
}
then
if( preloaded == 1 ){
start_your_page();
}
Here the code that will remove the img tag and replace it with a new one:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function() {
var parent = document.getElementsByTagName('img')[0].parentElement;
parent.removeChild(document.getElementsByTagName('img')[0]);
var new_img = document.createElement("img");
new_img.src = "https://upload.wikimedia.org/wikipedia/commons/6/69/600x400_kastra.jpg";
parent.appendChild(new_img);
});
<img src="https://www.w3schools.com/w3images/fjords.jpg">
I resolved the issue using code:
function displayImage() {
let image = new image();
image.src="source/of/image/returned/from/service";
image.addEventListener('load', function () {
document.getElementsByTagName('img')[0].src = image.src;
},false);
}
Here in code, I am attaching load event to image, source of image will be changed after image is loaded.

show alternate image if img src is not found - knockout

I have this piece of code.
<img data-bind="attr: {src: 'imagePath'}, style: { 'background-image': 'url('imagePath')' }" class="img-responsive">
The problem is it is showing two images. One is the image coming from src and other one coming from background image. My goal was to enable the background image when the src image is not available.
What you can do is create a custom binding, let's call it safeSrc.
In this binding, you listen to the load and error events of your image - rendering your image if it's loaded successfully and rendering a fallback if it is not.
In practice, it could look like the following:
ko.bindingHandlers.safeSrc = {
update: function(element, valueAccessor) {
var options = valueAccessor();
var src = ko.unwrap(options.src);
$('<img />').attr('src', src).on('load', function() {
$(element).attr('src', src);
}).on('error', function() {
$(element).attr('src', ko.unwrap(options.fallback));
});
}
};
And then, you can apply the binding like this:
<img alt="Foo" data-bind="safeSrc: {src: imageObservable, fallback: 'https://example.com/fallback.png'}" />
Note that this presumes you're using jQuery - but you can easily rewrite the event listener.
Finally, I would also like to say that you should be rendering a different src instead of the background image - unless you have a specific reason to require one?
Either way, you can simply change the line $(element).attr('src', ko.unwrap(options.fallback)); to $(element).css('background-image', 'url(' + ko.unwrap(options.fallback) + ')');.
JS Fiddle Demo
Here, you can see it all in action: https://jsfiddle.net/13vkutkv/2/
(EDIT: I replaced the cheeky hotlink to the Knockout JS logo with Placehold.it)
P.S.: Depending on how you wish to interact with the element in future (interacting with/updating the binding), you may wish to use applyBindingsToNode (i.e. the Knockout-way), rather than manipulating the src attribute directly on the DOM element.
To show alternate image if img src is not found make alternate image link in your server logic and use only src: 'imagePath' in your front-end
Or if it is important to do it in front-end, you should look at this post:
Display alternate image
I always check my images with a deferred object to be sure they will load. This is using the jquery deferred method, but you could use any deferred library. I coded this from memory, so there may be some errors.
<img data-bind="attr: {src: $root.imagePath()}, style: { 'background-image': 'url('imagePath')' }" class="img-responsive">
var myController = function()
{
var self = this;
this.imagePath = ko.observable('myPath.png'); // Make the image url an observable
var getImagePath = function(path)
{
var imagePath = this.imagePath();
isLoaded(imagePath).done(function(result)
{
// The image will load fine, do nothing.
}).fail(function(e)
{
self.imagePath('defaultImageOnFail.png'); // replace the image if it fails to load
});
};
getImagePath();
};
var isLoaded = function(img)
{
var deferred = new $.Deferred();
var imgObj = $("<img src='"+img+"'/>");
if(imgObj.height > 0 || imgObj.width > 0)
{
deferred.resolve(true);
}
else
{
imgObj.on("load", function(e)
{
deferred.resolve(true);
});
imgObj.on("error", function(e)
{
console.info("VoteScreenController.isLoaded URL error");
deferred.reject();
});
}
return deferred.promise();
};

Javascript get width of img from path

i think there should be an easy solution for this, but I can't figure it out.
What I'm trying to do is to get the width/height of an image by its path (not rendered on screen).
Like:
var img = ImageInfo(path);
alert(img.width);
(I want to do this in plain javascript)
You can do something like this:
function getImageSize(imgSrc) {
var imgLoader = new Image(); // create a new image object
imgLoader.onload = function() { // assign onload handler
var height = imgLoader.height;
var width = imgLoader.width;
alert ('Image size: '+width+'x'+height);
}
imgLoader.src = imgSrc; // set the image source
}
You basically create a new image using javascript. Assign the onload event, and then set the source and wait for image to load. when it's loaded the onload handler alerts the height and width of the image. check this jsFiddle
Let ImageInfo function to accept a callback(ie: make it async).
function ImageInfo(path, onLoad) {
var img = new Image();
img.src = path;
img.onload = function() {
onLoad(img);
}
}
Use it like:
ImageInfo(url, function(img) {
alert(img.width);
});
Try this:
var path = "http://images2.wikia.nocookie.net/__cb20110928222437/callofduty/images/4/4f/Personal_IW_FTW_Awesome_Face_100px.png";
var img = new Image();
img.src = path;
It's pretty simplified, but something alone these lines should work.
http://jsfiddle.net/s9QVp/1/

Checking if an image is missing from folder in javascript

I am making a small slide show application to show images inside an html.
The name of images are something like:
"MOD01_001.jpg"
"MOD01_002.jpg"
"MOD01_004.jpg" and so for...
Sometimes one or more images is missing and the previous images still is in the cache, so I can't check if the new image was loaded checking for the width/height properties.
What can I do to check if an images are missing from the list (I know I can't access the file info from inside client browser).
TIA
This loads them all in, so it could be really terrible:
var images = ['MOD01_001.jpg','MOD01_002.jpg','MOD01_003.jpg'];
for (i in images) {
checkIfImageExists(images[i]);
}
function checkIfImageExists(image_path) {
var img = new Image();
img.onerror = function(){
console.log('Could not load image: ' + img.src);
}
img.onload = function(){
console.log('Loaded image: ' + img.src);
}
img.src = image_path;
}

Categories

Resources