jQuery, JavaScript, HTML: how to load images after everything else is loaded? - javascript

I have a very complex page with a lot of scripts and a rather long loading time. On top of that page I want to implement the jquery Nivo Slider (http://nivo.dev7studios.com/).
In the documentation it says I have to list all images for the slider inside of a div#slider
<div id="slider">
<img src="images/slide1.jpg" alt="" />
<img src="images/slide2.jpg" alt="" title="#htmlcaption" />
<img src="images/slide3.jpg" alt="" title="This is an example of a caption" />
<img src="images/slide4.jpg" alt="" />
</div>
However I might have 10 images with a 1000x400px which is quite big. Those images would load when the page loads. Since they are in my header this might take quite a while.
I looking for a way to use any jquery Slider Plugin (like the nivo slider) but either dynamically load images or load all those images after everything else on my page has loaded.
Any idea how I could solve that?
Is there even a way to start a javascript process after everything else on the page has loaded? If there is a way I might have an solution for my problem (using the jquery ajax load() method) ... However I have no idea how to wait for everything else to load and then start the slider with all the images.

Here's what we did and its working great. We skipped setting src attribute of img and added img-location to a fake attribute lsrc. Then we load a dynamic image with lsrc value, and set the src of actual image only after its loaded.
Its not about faster loading, but its about showing the images only when its downloaded completely on your page, so that user do not have to see that annoying half-loaded images. A placeholder-image can be used while the actual images are being loaded.
Here's the code.
$(function(){
$.each(document.images, function(){
var this_image = this;
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
//this_image.src = options.loading; // show loading
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
var img = new Image();
img.src = lsrc;
$(img).load(function() {
this_image.src = this.src;
});
}
}
});
});
Edit: Trick is to set the src attribute only when that source is loaded in temporary img. $(img).load(fn); handles that.

In addition to Xhalent's answer, use the .append() function in jQuery to add them to the DOM:
Your HTML would just have:
<div id="slider">
</div>
And then your jquery would be:
jQuery(function(){
$("#slider").append('<img src="images/slide1.jpg" alt="" />');
});

check out jquery load() event, it waits for everything including graphics
$(window).load(function () {
// run code
});
on load you could then load the images using:
var image = new Image();
image.src = "/path/to/huge/file.jpg";
You can add a function onload to the image too
image.onload = function() {
...
}

I am using the below to power my slider and improve the page load performance.
for (var i = document.images.length - 1; i >= 0; i--) {
var this_image = document.images[i];
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
$(this_image).attr("src",lsrc);
}
}
}

the best way to use is b -lazy js.
bLazy is a lightweight lazy loading image script (less than 1.2KB minified and gzipped). It lets you lazy load and multi-serve your images so you can save bandwidth and server requests. The user will have faster load times and save data loaded if he/she doesn't browse the whole page.
For a full list of options, functions and examples go to the blog post: http://dinbror.dk/blog/blazy.
The following example is a lazy loading multi-serving responsive images example with a image callback :) If your device width is smaller than 420 px it'll serve a lighter and smaller version of the image. When an image has loaded it removes the loader in the callback.
In Html
<img class="b-lazy"
src="placeholder-image.jpg"
data-src="image.jpg"
data-src-small="small-image.jpg"
alt="Image description" />
In js
var bLazy = new Blazy({
breakpoints: [{
width: 420 // Max-width
, src: 'data-src-small'
}]
, success: function(element){
setTimeout(function(){
// We want to remove the loader gif now.
// First we find the parent container
// then we remove the "loading" class which holds the loader image
var parent = element.parentNode;
parent.className = parent.className.replace(/\bloading\b/,'');
}, 200);
}
});
Example

jquery has a syntax for executing javascript after document has loaded:
<script type="text/javascript">
jQuery(function(){
//your function implementation here...
});
</script>

Related

How to force/trigger the load of Wordpress native lazy loading images without scrolling?

I don't like lazy-loading because it looks quite ugly for the user in terms of UX. However, I understand the benefits (faster page load, low bandwidth, high PageSpeed scores etc.)
I am planning to write a javascript code which will:
Stay in the bottom > Wait for the page to fully load > After 3 seconds it will work > Force load all the images which were lazy-loaded previously during initial page load
With this, I won't lose any speed scores (because it will load as normal with lazy loaded images) But, also will load the full images when everything is done, so user won't notice. (we do the same for loading live chat scripts. It works pretty nice)
It will probably look something like this:
<script>
window.onload = function() {
setTimeout(function(){
var ForceLoadImages = document.createElement('script');
ForceLoadImages.type = 'text/javascript';
ForceLoadImages.src = 'link-to-the-script-to-force-load-images.js';
document.body.appendChild(chatScript);
}, 3000);
};
</script>
I am not a js expert. This was just a dummy example to give an idea. I am specifically asking how to write the content of that "link-to-the-script-to-force-load-images.js" part. Will appreciate any inputs.
There was a similar question here, but need an answer for Wordpress.
I guess that the wp lazy load uses data-src attribute to hold the image and when in view port, its adding the image to the src attribute.
Simplified like this:
<img data-src="URL"/>
*if its not like this, find in your source code the attribute where image is hold when out of view
What you need to do is select all images and change the data-src to src like this:
var images = document.querySelectorAll('img');
window.onload = function() {
setTimeout(function(){
for (var i=0; i<images.length; i++) {
if(images[i].getAttribute('data-src')) {
images[i].setAttribute('src',images[i].getAttribute('data-src'));
images[i].removeAttribute('data-src'); // optional if you need to remove data-src attribute after setting src
}
}
}, 3000);
};
<div class="container">
<img data-src='https://picsum.photos/id/237/200/300' />
<img data-src='https://picsum.photos/seed/picsum/200/300' />
<img data-src='https://picsum.photos/200/300' />
</div>
I just wanted to put the solution as an answer (thanks to kaize) who are looking for something like this. It is very clean and works nice:
<script>
var loadimages = document.querySelectorAll('img');
window.onload = function() {
setTimeout(function(){
//Force Load images
for (var i=0; i<loadimages.length; i++) {
if(loadimages[i].getAttribute('loading')) {
loadimages[i].removeAttribute('loading');
}
}
}, 3000);
};
</script>
Who is this for?
For those who does not like the user-experience of lazy loading images. But applying it due to PageSpeed scores.
Where to place this?
Place this to the bottom of your page.
What does this script do?
This script runs 3 seconds after the page loaded completely. It force-loads all the images which were waiting to get into the viewport to be lazy-loaded by removing the "loading" attribute. So that, you get good pagespeed scores for deferring image loads meanwhile keeping the user experience better. (Keep in mind that you lose the bandwidth advantage of lazy-loading concept)

Replace img src but have loading graphic display while image is downloading

I have a page that swaps some fairly large images in and out. There are too many to preload when the page initially loads so that is not an option. So what I need to do is load them as they are requested by the user. Right now I'm using jQuery to replace the img's src. This works fine but the images I am loading can be around 500KB and it looks bad as they paint down the screen as they are downloading. What I'd like to do is pop a loading gif on the page when the image is in the process of loading then have the loading gif disappear once the image is loaded. I'm struggling to find a way to do that though. Here is the JS/jQuery code that I have that just replaces the src.
var product = "bowl";
var image = "dog.jpg"; //this is actually pulled from a data attribute, but its just hardcoded here for an example
$("#images img[data-product="+product+"]").attr("src", "/img/tablesetting/"+image);
I made a working jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
I recently needed to do the same thing. Basically I wrapped the image in a container div. within the container I've added a span element with my ajax loader gif embedded. this span has to be hidden initially but gets visible when an ajax request is made. The span gets removed when the image is fully loaded.
before ajax call
$('#your_image_container').find('span').show();
on success
$('#your_image').attr('src', 'your/image/url').load(function() {
$('#your_image_container').find('span').fadeOut();
});
I made a jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
Preload the image.
var product = "bowl";
var imageSrc = "dog.jpg";
var imgEl = $("#images img[data-product="+product+"]");
// show loading graphic only if it's needed
var timer = setTimeout(function(){
imgEl.attr("src", "/img/loading.gif");
},50);
// preload image
var img = new Image();
img.onload = function() {
clearTimeout(timer);
imgEl.attr("src",imageSrc);
}
img.src = imageSrc;
$img.attr("src", newImage);
if (!$img.get(0).complete) {
$img
.hide()
.after("<img src=throbber>")
.on("load", function () {
$(this).show().next().remove();
});
}

Finding height of image using JavaScript - image load error

I can't seem to find the height of an image using Javascript on a Typo3 website.
Basically I have javascript that runs inside a $(document).ready(function () { .
It looks for an image on the page and finds its height & width, then carries out opperations based on the results.
Sometimes this works and sometimes it doesn't. Usually, I get a width value but no height. I suspect this is because the browser hasn't finnished loading the image.
To solve this I have included a 2second delay to ensure img is loaded before looking for its height. But that isn't a very good way of solving the problem, especially if someone has low download speeds.
How else could I check that an image is loaded fully before carrying out opperations?
Here is some HTML:
<div class="resize-thumb-img">
<img src="#.jpg" />
</div>
<div class="resize-thumb-img">
<img src="#.jpg" />
</div>
<div class="resize-thumb-img">
<img src="#.jpg" />
</div>
And some JS:
$(document).ready(function () {
setTimeout(myFunctionX, 2000);
function myFunctionX() {
$(".resize-thumb-img img").each(function(){ //for each image
console.log("working on image: "+$(this).width() +"x"+$(this).height());
/* MORE WORK HERE */
});
}
});
The console log can give results like 235x420 OR 235x0 OR 0x0
I found a solution which I think helps in this context. It checks an image to see if its width is "0". If it is, it waits 1 second and then tries again. If its not "0", it calls the function I had before. Might be useful to include || null to the first if statement - I havn't tested on all browsers.
$(document).ready(function () {
checkLoadState();
function checkLoadState() //checks to see if images are loaded before continuing
{
if ($(".resize-thumb-img img").width() != "0")
{
console.log("Images loaded. Resizig...");
myFunctionX();
}
else
{
console.log("Waiting for images to load.");
setTimeout(checkLoadState, 1000); // check again in a second
}
}
function myFunctionX() {
$(".resize-thumb-img img").each(function(){ //for each image
console.log("working on image: "+$(this).width() +"x"+$(this).height());
/* MORE WORK HERE */
});
}
});
You can try the below one:
$('img').each(function() {
$(this).attr('height',$(this).height());
$(this).attr('width',$(this).width());
});
This will help you to find the height of your image using jquery.
If you have control over the server-side scripts, couldn't you simply store the size of the bitmap in a database together with its filename? Then you could set the WIDTH and HEIGHT attributes of the IMG elements.
What you need to do is bind a function to the load event for any images that aren't yet loaded, something like this
function processImage(imageElement){
// do your stuff here
var img=$(imageElement);
console.log("working on image: "+img.width() +"x"+img.height());
}
$(document).ready(function () {
// iterate through the images
$(".resize-thumb-img img").each(function(){
var img = $(this);
if(img.width()==0 || img.height()==0){
// image has not fully loaded yet, so process it once loaded
img.on('load',function(){processImage(this);})
}else{
// image is loaded so process the image straight away
processImage(this);
}
})
})

How can I remove default image icon

Images in which I have facing the cross sign problem which is appear in chrome and IE
the scenario which i want from external java script file(i want something like this).
first image having a cross icon when image tag not find the image from the source. mozilla will handle this very smartly but chrome and IE show a cross icon which i don't want..
i find out the solution which is not generic i have to pass a transparent image url when image not getting the image from specified url on every image tag..
something like this
<img src="i/ibm.png" onerror="this.src='i/1x1trns.png';">
but in my page there are more than 20 image and in a whole project more than 200 so in that case i want to handle this from a single external javascript file ...
so any one how know about this problem please tell me a solution...Thnx for co-operation
It's a bit dirty to have jQuery defined in the <head /> tag but you'd need to do this for $.ready, if you can write your own $.ready then it'd be just a bit of code in our <head />.
OR
You'd need to add jQuery before you have those images.
Try this code
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("img").on("error", function() {
$(this).attr("src", "i/1x1trns.png");
});
});
</script>
<img src="not-a-valid-image.png" alt="Logo not found" />
</body>
I have used this way in one of my projects.
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
(function(img_elem) {
var img = new Image();
img.src = img_elem.src;
img.onerror = function() {
img_elem.src = 'i/1x1trns.png';
};
})(imgs[i]);
}
http://jsfiddle.net/Ypa7N/

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/

Categories

Resources