Asynchronous loading images with JavaScript - javascript

Is there a method for showing a loading image for dynamic images that are generated using Flickr? I have come across a way to do it as shown on the Wacom Community site but I have not been able to get it to work. Is there something simpler or does anyone have a better explanation than the originator of the technique from http://blog.realmofzod.com/asynchronous-image-loading-with-jquery/?

I just got this working. YMMV:
<img src="images/blank.gif" onload="replaceImage(this, 'flickrthumbnailimageurl')"
width="75" height="75" />
And then replaceImage:
function replaceImage(img, replacementImage)
{
img.onload = null;
img.src = replacementImage;
}
blank.gif is just a 1x1 pixel solid gray image. Basically, the idea is that this blank image is loaded and expanded to 75x75 (to preserve layout). That almost immediately fires the onload handler, which changes the image's source to the desired image. It has the effect you desire.

could do it with jquery:
<img src="http://myimages.com/loaderImage.jpg" id="imgIdLoading" />
<img src="http://flickr.com/image.jpg" id="imgId" style="display:none;" />
$('#imgId').load(function(){
// ... loaded
$('#imgIdLoading').remove();
$('#imgId').show();
}).error(function(){
// ... not loaded
$(this).attr('src','/whatever/error.png');
});

Related

How to replace HTML img broken by missing or erroring image src

I have following code:
<img src="test.jpg" width="20" height="20"> some content here
When image is not found, it shows like following:
This behavior is different according to browsers.
I want to display transparent box(plain white) or some good looking container(empty box) that will look same in all browsers. I have tried with alt tag, but it does not work.
How can I achieve this ?
Demo: Sample
<img src="img_girl.jpg" width="20" height="20"> some content here
You can use the error handler with onError. But make sure to cancel the onError handler after it is invoked, because if your backup-image is missing, this will cause an infinite loop of server requests -- not good! Handle it like this...
<img src="test.jpg" width="20" height="20" onerror="this.onerror=null;this.src='imageNotFound.gif';">
By setting this.onerror=null;, we are preventing an infinite loop of server requests. Then imageNotFound.gif will display for users if the image is there.
POD (Source: MDN Web Docs: GlobalEventHandlers.onerror)....
The reason we have the this.onerror=null in the function is that the browser will be stuck in an endless loop if the onerror image itself generates an error.
Since you're using Angular you can simply use onError to show your fallback/error image in case that your initial src could not be loaded:
<img [src]="invalidPath" onError="this.src='images/angular.png'"/>
You need to use the backend programming to determine if the path exists and contains an image then display it. If the path does not exist or does not contain an image then you can decide to display a default image or any component of your choice.
In PHP you can do it as follows:
<?php
if (file_exists('test.jpg')) {
echo "<img src='test.jpg'>";
} else {
echo "<img src='default.jpg'>";
}
?>

I can't validate tag img

this is Augusto from Italy
when migrating from HTML to XHTML I am facing an unresolved problem
In html code I have an image (bigimg) that is at first charged via Js charged by the body onload, then other images, out of a preview series, are being charged, thus replacing my image,
In body:
<body onload="...........;viewimgac('images/accessories/img01cs.jpg');...............">
The function is:
// the waiting image view and the main image loading is managed
function elaboraimgac(urlimg) {
document.getElementById('dattesa').style.filter = "alpha(opacity:"+90+")";
document.getElementById('dattesa').style.MozOpacity = 90/100;
document.getElementById('dattesa').style.KHTMLOpacity = 90/100;
document.getElementById('dattesa').style.opacity = 90/100;
MM_changeProp('dattesa','','style.visibility','visible','LAYER'); // div is made visible through the waiting gift.
document.getElementById('bigimgid').src = urlimg; // I load the image
The code page shows:
<img src="#" id="bigimgid" style="position:absolute;left:0px;top:0px;" onload="finecaricimg()" alt="" />
the <img> tag, as it is, prevents XHTML validation. I have to eliminate onload="finecaricimg()", being the function allowing view of image duly placed in the page using the image size that is available after loading.
I acted this way:
1) change <img tag
<img src="#" id="bigimgid" style="position:absolute;left:0px;top:0px;" alt="" />
2) I added :
function elaboraimgac(urlimg) {
//to Js elaboraimgac function
//........
//........
document.getElementById('bigimgid').onload = finecaricimg(); // the specific function is called after loading
}
To intercept the image loading end and recall the loading end function
Unfortunately the procedure is unsuccessful. Via alert I realized that the image size – when the loading end is charged – is zero, as if finecaricimg() is charged right after the .src processing and not when the image loading is over.
I tried to add:
document.getElementById('bigimgid').src = urlimg;alert("AAAAA"); // load image
then, when the alert window appears, I wait for some seconds before clicking OK. This way the image size is correct and the image is properly placed in the page.
I am unable to understand, as the code seems the correct one.
I am therefore asking for your suggestion.
....onload = finecaricimg();
You just called your function immediately and assigned its result to onload (just like any other function call).
You want to assign the function itself, without calling it.
I have solved in this way:
var img = document.getElementById("bigimgid");
img.src = urlimg; // carico l'immagine
img.addEventListener("load", finecaricimg); // a fine caricamento richiamo la funzione specifica
thanks

Relative path in preloading images

This may be a dumb question, but I've a real confusion and want to get an opinion from somebody who knows this in-out.
Preloading images can be done either via JavaScript or CSS (to name two which I'm considering). I read the tutorials that if the browser finds the same image path again, it would render the cached image.
If I preload images like:
<img src="../images/bg.jpg" alt="background" width="1" height="1" style='display:none' />
and
<img src="images/bg.jpg" alt="background" />
Similar with javascript:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
preload([
'../img/imageName.jpg',
'img/imageName.jpg' // case when using this script in a different hierarchical level)
]);
Will the second call result into rendering of the image from the cached version or it will not work because the image path specified is different (though ultimately it refers to the same file).
Thanks in advance.
I realise this is and old one but I get this one all the time from interns - so here goes...
Even though the onload function is in the JS file asking/telling the browser to look for the image; it is the browser looking for the image and is telling the JS that the image/s loaded.
So your image path in the JS should be the same as how you would enter it in the HTML.
PS: I noticed in your HTML the image folder is "/images" and in your JS the folder is "/img"

Preloading images in Javascript

I have created a simple photo gallery viewer, and I would like to preload the images in the background, and then run a function when they are done.
My question is, how do I do that?
var image = new Image();
image.src = "http://foo.com/myimage.jpg";
//if you have a div on the page that's waiting for this image...
var div = getElementById("imageWrapperDiv");
//you can set it on the image object as the item to draw into...
image.myDiv = div;
image.onload = function(){
//do whatever you're going to do to display the image
//so in this example, because I have set this objects myDiv property to a div on the page
// I can then just populate that div with an img tag.
//it's not the most elegant solution, but you get the idea and can improve upon it easily
this.myDiv.innerHTML = "<img src='" + this.src +"'>";
}
Once the image loads, it's in the browser's cache, so, if you use the src property you can draw it anywhere on the page and it will display instantly.
To preload an image use the <link> tag and add preload to the rel-attribute:
<link rel=preload href=path/to/the/image.jpg as=image>
Alternatively in Javascript:
var preImg = document.createElement('link')
preImg.href = 'path/to/image.jpg'
preImg.rel = 'preload'
preImg.as = 'image'
document.head.appendChild(preImg)
The preload value of the element's rel attribute allows you to
write declarative fetch requests in your HTML , specifying
resources that your pages will need very soon after loading, which you
therefore want to start preloading early in the lifecycle of a page
load, before the browser's main rendering machinery kicks in. This
ensures that they are made available earlier and are less likely to
block the page's first render, leading to performance improvements.
Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
I like this CSS method versus the typical Javascript function:
Place this in your CSS file:
div#preload { display: none; }
Place this at the bottom of your HTML document:
<div id="preload">
<img src="http://domain.tld/image-01.png" width="1" height="1" alt="Image 01" />
<img src="http://domain.tld/image-02.png" width="1" height="1" alt="Image 02" />
<img src="http://domain.tld/image-03.png" width="1" height="1" alt="Image 03" />
</div>
This method ensures that your images are preloaded and available for use elsewhere in the document. Just remember to use the same path as the the preloaded images.
http://perishablepress.com/pure-css-better-image-preloading-without-javascript/

Javascript replace( ) function running more than once on the same image

I'm running a Javascript replace function to replace standard images with class="replace-2x"on my jQuery Mobile site with Retina-quality images if the user is on a mobile device with Retina display. For example, on a Retina device, logo.png will be replaced with logo#2x.png. The JS function is here:
function highdpi_init() {
$(".replace-2x").each(function () {
var src = $(this).attr("src");
$(this).attr("src", src.replace(".png", "#2x.png").replace(".jpg", "#2x.jpg"));
});
}
$(".page").live('pageinit',function(event){
highdpi_init();
});
I'm now running into an issue where the replace function is running more than once. So for example, it replaces logo.png with logo#2x.png as the page is loading, but then as the page continues to load, it KEEPS replacing .png with #2x.png in the img src over and over so that the image tag ends up looking like this:
<img src="mobile/images/logo#2x#2x#2x#2x#2x#2x#2x#2x#2x#2x#2x.png" class="replace-2x" alt="logo" width="200">
How can I prevent this from replacing on a single img element more than once? Keep in mind, I will have multiple images on the same page, so the function will need to apply to all images, but only one time each.
The problem is surely that your 'pageinit' event is being called more than once. You can either follow MДΓΓ БДLL's idea (which won't work if images are dynamically added) or you can make your handler smarter so that it doesn't replace the src if it already was replaced
function highdpi_init() {
$(".replace-2x").each(function () {
var $this = $(this);
var src = $this.attr("src");
$this.attr("src", src.replace(".png", "#2x.png").replace(".jpg", "#2x.jpg"));
// Remove the class so it doesn't replace it again
$this.removeClass('replace-2x')
});
}
You don't need JS for this, you could do it in CSS only.
<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" href="/css/highdpi.css"/>
You could make your images look like
<img src="transparent.gif" class="logo-a" alt="logo" width="200" />
And in highdpi.css you could do
img.logo-a {
background-image: url('file#2x.png')
}
And in lowdpi.css
img.logo-a {
background-image: url('file.png')
}
Using .one() should work since it is just a binding and if you are using Jquery Mobile the way that is suggested it will be just fine. That is unless you are passing back the html from the server. In which case it would be a good idea to add an extra condition to make sure that the src doesn't already have #2x.png before replacing.
There is disappointingly little documentation on pageinit on the offical jQuery Mobile docs. So I'm going to speculate here. It looks like pageinit is used to fire events for when a specific DOM element has finished loading, since it may not have been loaded on the initial page load (deferred until needed). That being said, it may be that adding/altering images to the DOM element in question fires the pageinit again. Could you tag each updated image with something that says, 'hey, I've already been updated to 2x'? Something such as
$.data(targetimg, 'retinafied', true);
And then check for that value before replacing the src?

Categories

Resources