I have to load image sequence animation about 60 images array. I want this particular sequence loaded separately. means that images loading time does not affected to whole page load time. because it is taking too much time to load page with image sequence animation. Currently i have added all 60 images of sequence in HTML code and set "display:none" to load with page.
Is there any possibility to load this images separately or load after my whole html page loaded. or any other better solution.
Thanks in advance.
Load them dynamically using javascript/jquery
var imagePaths = ["img1.png", ....];
$(document).ready(function(){
for(var i=0; i<imagePaths.length; i++) {
var newImg = $('<img style="display:none;" />'); //Add any class or attribute you want or anything for images.
newImg.bind("load", function(){
$(this).show();
});
newImg.attr("src", imagePaths[i]);
$(parentSelector).append(newImg);
}
});
When you load dynamically from script, your HTML page would have loaded and be ready for use. And later all the images will come into view gradually.
Edit:
In addition if you want to keep your image hidden until it gets completely loaded, you could initially set display:none; inline and attach an onload listener, display:block there.
Hope this helps. Let me know if I missed anything.
Yes it is possible.
var images[60];
var names[60]={"img1.jpg","img2.jpg"...}
function loadImages() {
for(var i=0;i<60;i++) {
images[i] = new Image();
images[i].src = "www.myWebPage.com/"+names[i];
}
}
This function will now load images. Just make sure to call it after your page loads.
<body onLoad="loadImages()">
...
</body>
Related
For some reason, when I use the attribute onload on my img tag, it causes my images to flicker. Ideally, when I load the page, an image is displayed and when I refresh the page, the image is changed.
Here's my tag as well as the function for it:
HTML
<img id="randomimage" onload="randomImg()" src="images/carmainpic.jpg" alt="main pic of car"/>
JavasScript
function randomImg(){
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
Because the function you're calling changes the image's src to a random pick from the array, triggering a new load event, which changes the src randomly again, etc. On at least some browsers the cycle probably stops when you happen to assign the URL the image already has, too.
If your goal is to just show one of those images, at random, you can do that by leaving src off the img entirely and then adding it (once) with script (either immediately following the img in order to avoid your layout having to be adjusted when you add it, or in script at the end of the page if you prefer; no need to wait for any event):
<img id="randomimage" alt="main pic of car"/>
<script>
(function() {
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random() * images.length); // <== Note change, so adding images to the array Just Works
document.getElementById("randomimage").src=images[num];
})();
</script>
Even if you put the script immediately after the <img ...> tag, the img element will be available to the script. So your choice whether to do it inline or with the other scripts at the end of the page.
The randomImg function is called every time the image loads. You can use a flag variable to make sure that you only change the image once:
var changed = false;
function randomImg(){
if (!changed) {
changed = true;
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
}
The problem is that you are listening to the load event on the image, instead of the page.
onload="randomImg()"
So, as soon as the first image loads, it triggers the function randomImg which causes change of src attribute on the image. So the browser will attempt to assign a new image to the element, and yet another load event is triggered, which repeats the entire cycle.
Instead, if you want to choose a random image when the page loads, you can listen to DOMContentLoaded event on the document, and choose a random image.
document.addEventListener("DOMContentLoaded", function() {
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
console.log("Showing: " + images[num]);
});
<img id="randomimage" src="images/carmainpic.jpg" alt="main pic of car"/>
Note: Since you are selecting a random image, it is not guaranteed that you will always get a different image when the page is refreshed. Instead, if you must get a different image on refreshing the page, you can perhaps persist the image identifier in localStorage, and use that to determine the next image to display.
Well you can use $(document).ready(function(){}) to do that. Because you want when charge the page that function execute it.
$(document).ready(function(){
function randomImg(){
var images=["https://www.bensound.com/bensound-img/romantic.jpg","https://www.psdstack.com/wp-content/uploads/2016/10/featured-copyright-free-mages.jpg","http://shaebaxter.com/wp-content/uploads/2015/04/Life-of-Pix-free-stock-photos-sea-peaople-water-waves-back-Sunset-Joshua-earle-1024x682.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
randomImg();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="randomimage" src="" alt="main pic of car"/>
I inherited a project where a page is loaded, then code attached to that page fills in a div with dynamically generated html - it basically fills an existing div with a html string.
This string contains links to images, etc.
I want to tell when all the images, etc have loaded- I cannot seem to get any jQuery standard checks
to work - ie I have tried attaching $(window).load() after the dynamic stuff has been inserted.
I am wondering if I should write $(window).load() dynamically as well, or if there is any other
method- ie $("#thediv").load (doesn't seem to work. I cannot query all the new html for image tags, etc-
too much stuff is being put in.
The $(window).load() doesn't work for dynamic content as far as I know. You can use the .load event for each image separated. Here's an example:
var container = $("<div> ... Stuff ... </div>");
var images = container.find('img');
var imageIdx = 0;
images.load(function(){
imageIdx++;
if (imageIdx == images.length){
callback();
}
});
Where callback() is the function that runs after all images where loaded.
From my comment: window load applies to the initial page load only. Not dynamic loading of content within it. Attach load handlers to each loaded image element and count them.
This is the shortest version I could come up with for you:
// After HTML load finishes
var img = 0;
var imgCount = $("#thediv img").load(function(){
if (++img == imgCount){
// We are done loading all images!
}
}).length;
$(window).ready() only applies to the content within the HTML file and you can only use load to attach an onload event handler to a specific image (not a container), something like this might work for you.
window.ImageLoadHandled = false;
window.ImageLoadCount = 0;
function ImageLoadHandler() {
// guard against calling this function twice
if(window.ImageLoadHandled) return;
window.ImageLoadHandled = true;
// All images have loaded || timeout expired...
}
$("#myAjaxedDiv img").load( function() {
window.ImageLoadCount++;
if( window.ImageLoadCount == $("#myAjaxedDiv img").length ) {
// all images in #myAjaxedDiv have loaded
ImageLoadHandler();
}
});
// if images haven't loaded after 5 seconds, call the code
setTimeout( ImageLoadHandler, 5000 )
The only problem with this is that if an image fails to load for whatever reason, the code will never be hit, which is quite risky. To counteract this I'd recommend creating a setTimeout() method to call your code after a few seconds timeout in-case there is a problem loading images (client or server side) and I've also taken #TrueBlueAussie's correction into account in the edit.
Your alternative is to preload the images with your HTML page
I am using jQuery load() to check if an image that I'm replacing the src on is loaded. Sometimes it appears to get stuck or hang though. I have a jsFiddle link below to check out. To make the loading graphic get stuck on the page click one of the buttons twice.
http://jsfiddle.net/dmcgrew/LLMs8/3/
This "almost" replicates a problem on a site I'm currently building, but I think the issues are related. On the site I'm building this "hanging" only happens when I do the following steps:
Click Image 3 button
Click Hide button
Click Image 3 button again
The loading graphic is now stuck on the page.
Here is my JS...
$("button").not("off").bind("click", function(){
var imgPath = $(this).attr("data-image"); //grab image path from data attr
console.log(imgPath);
$(".loading").show(); //show loading gif
$("img.the_image").hide(); //hide the img
$("img.the_image").attr("src","http://farm7.staticflickr.com/"+imgPath).load(function() {
$(".loading").hide(); //hide loading gif
$("img.the_image").show(); //show the newly loaded img
});
});
$("button.off").bind("click", function(){
$("img").hide();
});
Is load() the best way to check if an image has been loaded? Is there a better way that I should replace the image and check if its loaded (maybe AJAX?).
You have two issues: First, your code attaches the load handler multiple times, which is causing funky behavior. Second, your code doesn't handle multiple clicks on the same element in a row. Try this:
http://jsfiddle.net/E3Avx/
$("button").not("off").bind("click", function () {
var imgPath = $(this).attr("data-image"); //grab image path from data attr
var newImgPath = 'http://farm7.staticflickr.com/' + imgPath;
if ($('img.the_image').attr('src') != newImgPath) {
$(".loading").show(); //show loading gif
$("img.the_image").hide(); //hide the img
$("img.the_image").attr("src", newImgPath);
}
});
$("img.the_image").load(function () {
console.log('load handler');
$(".loading").hide(); //hide loading gif
$("img.the_image").show(); //show the newly loaded img
});
$("button.off").bind("click", function () {
$("img").hide();
});
This problem seems to be related to you trying to load() the same image twice, as the src doesn't actually change I think it's causing problems.
The easiest way to deal with it is just to check if the current src matches the src that has been selected, eg:
if($('img.the_image').attr('src') != 'http://farm7.staticflickr.com/' + imgPath) { }
http://jsfiddle.net/LLMs8/7/
I'm wondering if there is a way to detect load event of multiple images (particularly, a function should execute when the last image in a given set has completed loading).
For instance, an user clicks on a link and lighbox appears with 10 images. When all images have loaded, loading bar should disappear.
jQuery(".lightbox-image").each(function(){
var image = jQuery(this);
jQuery('<img />').attr('src', image.attr('src')).load(function(){
hideLoadingBar();
});
});
This unfortunately triggers hideLoadingBar(); too early (after one image has completed loading).
P.S.
I also need my function to work after images have been cached so: jQuery('#img1, #img2').load(); won't work.
Check out this jQuery imagesLoaded plugin, it should suit your needs I think.
Well, it seems that no one has better idea, so below is my solution/workaround. The other answer to this question is probably what you want to use because it's a library created specifically for that but here's the solution that I'm going to use because it's shorter and simple:
var allImages = jQuery(".lightbox-image").length;
var counter = 0;
jQuery(".lightbox-image").each(function(){
var image = jQuery(this).find('.myimage');
jQuery('<img />').attr('src', image.attr('src')).load(function(){
counter++;
if(counter >= allImages){
hideLoadingBar();
}
});
});
Works for cached images and not cached images.
I have run into numerous sites that use a delay in loading images one after the other and am wondering how to do the same.
So i have a portfolio page with a number of images 3 rows of 4, what i want to happen is for the page to load,except for the images in img tags. Once the page has loaded i want images 1 of each row to load then say 0.5 seconds later the next image in the row(s) and so no. I'm going to have a loading gif in each image box prior to the actual image being displayed.
I know its doable but cant seem to find the term for doing this. This is purely for looks as it is a design site.
Thanks for the help.
This is very easy to do in jQuery
$('img').each(function(i) {
$(this).delay((i + 1) * 500).fadeIn();
});
Fiddle: http://jsfiddle.net/garreh/Svs7p/3
For fading in rows one after the other in a table it just means changing the selector slightly. Remember to change from div to img -- I just used div for testing
$('tr').each(function(i) {
$('td div', this).delay((i + 1) * 500).fadeIn();
});
Fiddle: http://jsfiddle.net/garreh/2Fg8S/
Here is what you can do, you can load the image tags with out the src and using a custom property:
<img alt='The image' path='image/path.jpg' />
then you can use javascript to load the images when the site is loaded or whenever you please;
// simplified
window.onload = function () {
var images = document.getElementsByTagName('img');
// loop and assign the correct
for (var i =0; i < images.length;i++){
var path = images[i].getAttribute('path');
images[i].src = path;
}
}
I hope you get the concept of how the images are delayed
**please note the path attribute is not a standard one.
The easiest way I can think to do this is to have a table set up that will eventually hold the image tags, but have none on load. Javascript can loop through an array of image urls, and insert those image tags into random locations on the table.
If you want to have the delay, setInterval is the perfect tool. http://www.w3schools.com/jsref/met_win_setinterval.asp
// You can hard-code your image url's here, or better still, write
// a server-side script that will read a directory and return them
// so it is fully dynamic and you can add images without changing code
unpickedImages = array();
// Start loading
loadAllImages = setInterval( insertImage, 600 );
function insertImage() {
if( unpickedImages.length > 0 ) {
var imageUrl = unpickedImages.shift();
// pick empty x, y on your table
// Insert the image tag im that <td></td>
} else {
clearInterval( loadAllImages );
}
}
You really don't need javascript to do this. If you specify the image sizes in the HTML or CSS, the browser will layout and display the page while loading the images, which will likely be loaded in parallel. It will then display them as soon as it can.
That way if users re-visit your site and have the images cached, they all show up immediately. If you have a script to load the images after a delay, you are making visitors wait for content unnecessarily and all their efforts to have a faster browser and pay for a fast internet connection has gone to waste.