Delay image loading with JavaScript - javascript

i currently need to load 123,543 images from my server but every image must go through a PHP script to generate it, the problem is that my server is very weak and it crashes after loading about 600 images, so i'm asking for a Javascript that will load 2 images / second, if possible.
Thank you.

You can use http://www.appelsiini.net/projects/lazyload
$(function() {
$("img.lazy").lazyload({
event : "sporty"
});
});
$(window).bind("load", function() {
var timeout = setTimeout(function() { $("img.lazy").trigger("sporty") }, 5000);
});

Assuming you want to place all the images in a container with id 'container', this code does the trick:
var images = [
'image1.jpg',
'image2.jpg'
],
container = document.getElementById('container');
function loadNextImage(index) {
var index = index || 0,
imageUrl = images[index],
image = document.createElement('img');
image.src = imageUrl;
container.appendChild(image);
if (index + 1 < images.length) {
setTimeout(function(){loadNextImage(index + 1)}, 500);
}
}
loadNextImage();

Related

Preload json files generated by bodymovin/lottie loaded twice by PreloadJS

I am trying to create a preload for my site via the PreloadJS library.
On the site I created a dozen items via bodymovin / lottie.
Bodymovin create json files with all the information of the graphic elements and animations. With Lottie it is rendered as svg.
Without PreloadJS the json file is normally loaded by the broswer, but with PreloadJS it is first loaded by the broswer and then preloaded a second time.
So I wondered what I was doing wrong.
Example of a duplicated preload file
I had the same issue with images (loaded twice), but I solved adding "false" to "new createjs.LoadQueue(false)" but with all other files type (json, js, css) the load twice issue is still there.
The preload part
var preload;
function setupImgs() {
var images = $('#main').find('img').map(function(){
return $(this).attr('src')
}).get();
var i = 0;
$.each(images, function(index, value) {
preload.loadFile({id:'img0'+i, src:value});
i++;
});
}
function setupSvgs() {
var pathjson = basepath + 'assets/img/';
var json = [
pathjson+'contatti.json',
pathjson+'grafica.json',
pathjson+'lavori.json',
pathjson+'packaging.json',
etc.....
];
var i = 0;
$.each(json, function(index, value) {
preload.loadFile({id:'json'+i, src:value});
i++;
});
}
function startPreload() {
$('#preload').css({'display': 'block'});
preload = new createjs.LoadQueue(false);
preload.on('fileload', handleFileLoad);
preload.on('progress', handleFileProgress);
preload.on('complete', loadComplete);
preload.on('error', loadError);
setupImgs();
setupSvgs();
}
function handleFileLoad(event) {
//console.log("A file has loaded of type: " + event.item.type);
}
function loadError(evt) {
console.log("Error!",evt.text);
}
function handleFileProgress(event) {
var p = Math.round(event.loaded * 100);
$('.preload-perc').text(p + '%');
$('.preload-bar').css({'width': p + '%'});
}
function loadComplete(event) {
console.log("Finished Loading Assets");
}
startPreload();
The Lottie part
var ID = document.getElementById('servizi');
var preload_logo = lottie.loadAnimation({
container: ID,
renderer: "svg",
loop: true,
autoplay: true,
path: basepath+'assets/img/servizi.json',
rendererSettings: {
progressiveLoad: true,
}
});

How to preload images during a looped array for background images

I've written a simple loop that cycles through a series of images in an array into the background-image property of an element. The problem is that due to the fact that the images are loading, the animation is going haywire when everything is initially loading. I'm trying to set up a preloading workflow where:
the entire loop is blocked by waiting until the first image is fully loaded
every time a new image is fully preloaded, it begins preloading the following image
the preloading must stop when the array is over and use cached images so it's easy on the browser and doesnt just keep loading the same array on images over and over eternally.
Any help?
http://codepen.io/jeremypbeasley/pen/JoZzyo?editors=001
var photoSet = [
"https://farm6.staticflickr.com/5475/9790841974_182a06590a_o.jpg",
"https://farm3.staticflickr.com/2840/9042399407_bf04388aca_o.jpg",
"https://farm6.staticflickr.com/5504/14634417581_626ea1a835_o.jpg"
];
var p = photoSet.length;
console.log(p);
var i = 1;
function loopPhotos() {
setTimeout(function() {
$('div').css({'background-image': 'url(' + photoSet[i] + ')',});
i++;
console.log(i);
// call the next indexed image and begin to preload it
var img = new Image();
img.src = photoSet[i];
if (i >= p) {
i = 0;
// stop preloading images, somehow used images that are cached so the browser isn't working eternally reloading the same X number of photos.
}
loopPhotos();
}, 2000)
}
$(document).ready(function() {
// load first image
var firstImg = new Image();
firstImg.src = photoSet[0];
// when first image is loaded, apply it to background and begin looping
if (firstImg.complete) {
$('div').css({'background-image': 'url(' + firstImg.src + ')',});
loopPhotos();
console.log('first image loaded!');
}
});
This will do it
var photoSet = [
"https://farm6.staticflickr.com/5475/9790841974_182a06590a_o.jpg",
"https://farm3.staticflickr.com/2840/9042399407_bf04388aca_o.jpg",
"https://farm6.staticflickr.com/5504/14634417581_626ea1a835_o.jpg"
];
function preloadImageAndAct(src, action){
var img = new Image();
img.onload = action;
img.src = src;
}
function showImage( src ){
$('div').css({
'background-image': 'url(' + src + ')',
opacity: 1
});
}
var nextImage = 0;
function loopPhotos() {
console.log('Preload and show image #', nextImage);
var nextSrc = photoSet[nextImage];
preloadImageAndAct( nextSrc, function(){
showImage( nextSrc );
setTimeout( function() {
nextImage++;
nextImage %= photoSet.length;
loopPhotos();
}, 2000);
});
}
$(document).ready(function() {
loopPhotos();
});
Demo at http://codepen.io/gpetrioli/pen/rarPay
Keep in mind that you cannot transition the background-image. If you want transition for the change of images you need to either use two elements or fade the element out / change src / fade the element in.
AS for the caching, once they have been loaded once they are automatically cached by the browser so there should be no issue with that.

Change background-image after specified time

I'm very new to javascript, so apologies that I haven't even attempted this as I have no clue how to even begin.
I have 3 images. Image1 is a png file, and Image2 and Image 3 are animated gifs.
What I need is very specific however. I would like Image1 to change to Image 2 after x seconds, and then change to Image3 after y seconds. Once Image3 is loaded I would like that gif to remain as the page background.
Any help would be much appreciated...
Okay so this is what I have at the moment,
var delay1 = 104000;
var delay2 = 14000;
setBackground('Image1.png');
setTimeout(function() {
setBackground('Image2.gif');
setTimeout(function() {
setBackground('Image3.gif');
}, delay2);
}, delay1);
function setBackground(src) {
image.style.backgroundImage = 'url('Image1.png + Image2.gif + Image3.gif')';
}
When run, no background image loads at all. Sorry if i'm being a complete moron. Like I said, i'm new to javascript...
You are looking for setTimeout function. It accepts two arguments: function and delay (ms), function will be called after delay.
var delay1 = 2000; // 2 seconds
var delay2 = 3000; // 3 seconds
setBackground('image-1.png');
setTimeout(function() {
setBackground('image-2.gif');
setTimeout(function() {
setBackground('image-3.gif');
}, delay2);
}, delay1);
function setBackground(src) {
image.style.backgroundImage = 'url(' + src + ')';
}

Jquery to let my banner images load first before it animates

I have created a banner image slideshow in jquery. Actually I just found the code somewhere, I can't remember. It starts to animate even the banner images are not yet fully loaded that makes the banner slideshow animates it's image description without images.
Anyone? please help me to modify the code and let it run by allowing the background images load first before it runs the slideshow animation.
Thank you.
(function ($) {
// Original JavaScript code.
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = 'http://www.site.com/sites/all/themes/layoutph/images/bg01.jpg';
backgrounds[1] = 'http://www.site.com/sites/all/themes/layoutph/images/bg02.jpg';
backgrounds[2] = 'http://www.site.com/sites/all/themes/layoutph/images/bg03.jpg';
backgrounds[3] = 'http://www.site.com/sites/all/themes/layoutph/images/bg04.jpg';
var customtitle = [];
customtitle[0] = "Welcome to Site";
customtitle[1] = "Site joined force with Site Foundation";
customtitle[2] = "Site Foundation school campaigns for 2014";
customtitle[3] = "New York visited by Site Foundation";
function changeBackground() {
if(currentBackground > 3 ) currentBackground = 0;
currentBackground++;
$('.masterbg').fadeOut(1000,function() {
$('div.slogan').text( customtitle[currentBackground] );
$('.masterbg').css({
'background-image' : "url('" + backgrounds[currentBackground] + "')"
});
$('.masterbg').fadeIn(1000);
});
setTimeout(changeBackground, 4000);
}
setTimeout(changeBackground, 4000);
})(jQuery);
var UserimageObj = new Image();
UserimageObj.src = "someimg.jpg";
//load the user image before doing anything
UserimageObj.onload = function () {
//do your stuff here
};
Is this what you were looking for?

Canvas load image before anything starts?

When I play my game and click space I show a pause screen with info and images. However the images dont show for like 5 seconds after the page is loaded. I guess this is because they are still loading. How can I prevent canvas from running until the images are loaded?
http://www.taffatech.com/Snake.html
click space straight away.
then click it again, wait 6-10 seconds and press it again.
this is the code for showing the images:
if(level == 1)
{
var img = new Image();
img.src = 'egg.png';
con.drawImage(img,350,40);
}
else if(level ==2)
{
var img = new Image();
img.src = 'baby.png';
con.drawImage(img,350,40);
}
else if(level ==3)
{
var img = new Image();
img.src = 'adult.png';
con.drawImage(img,350,40);
}
else
{
var img = new Image();
img.src = 'ultimate.png';
con.drawImage(img,350,40);
}
You just need to delay the execution of other scripts until the image you desire has been loaded. In your JavaScript, whenever you want to preload your image, you can use the following code as a guideline:
function onImageLoad(e) {
// Put code here to start your canvas business.
};
var image = new Image();
image.addEventListener('load', onImageLoad);
image.src = 'the/path/to/your/image.whatever'
Your onImageLoad function could render your image to the canvas (so the image load happens when you press pause), or you could have this script execute at the beginning and the function simply stores the image into a global variable. Up to you!
Hope this helps :)
You can keep all the image paths in an array and load all the images before starting
var imageObjects = [];
function loadImages(images, onComplete) {
var loaded = 0;
function onLoad() {
loaded++;
if (loaded == images.length) {
onComplete();
}
}
for (var i = 0; i < images.length; i++) {
var img = new Image();
img.addEventListener("load", onLoad);
img.src = images[i];
imageObjects.push(img);
}
}
function init() {
alert("start game");
// use imageObjects which will contain loaded images
}
loadImages(["egg.png", "baby.png", "adult.png", "ultimate.png"], init);
waitForImages jQuery plugin
GitHub repository.
$('selector').waitForImages(function() {
alert('All images are loaded.');
});

Categories