I have an automatic slideshow on the main page of some site. Images are rotating every 10 seconds, but when they appear for the first time they aren't already loadead (I guess), so a blank is show.
I think that preloading these images they will show fine, but I don't know how to preload them. I use the following code to preload all the images of the page, but it doesn't seems to work:
function preloadAllImages() {
for (i = 0; i < document.images; i++) {
var img = new Image();
img.src = document.images[i];
}
}
So, how can I make this work?
Try
function preloadAllImages() {
for ( var i = 0; i < document.images.length; i++) {
var img = new Image();
img.src = document.images[i];
}
}
I believe you are missing the length attribute.
Related
I'm trying to create a scroll-based animation functionality similar to this project.
https://codepen.io/j-v-w/pen/ZEbGzyv
But the thing is, when I define and execute this snippet inside useEffect, this will cause the images to flick, meaning they are not preloaded
const preloadImages = () => {
for (let i = 1; i < frameCount; i++) {
const img = new Image();
img.src = currentFrame(i);
}
};
preloadImages();
But if I add console.log(img), it will load images and work fine.
const preloadImages = () => {
for (let i = 1; i < frameCount; i++) {
const img = new Image();
img.src = currentFrame(I);
console.log(img)
}
};
preloadImages();
Is there any way to load the images without logging it?
this is my whole code for refrenece
https://replit.com/#farhadham/GiantTepidGraduate#src/App.jsx
I am working on a slideshow/carousel for my website. I found this code online and would like to know how to add links to the images presented in the slideshow. I am open to any other suggestions for slideshows.
<!-- Showcase/Banner Image -->
<section id="banner">
<script>
var i = 0; // Start point
var images = [];
var time = 2500;
// Image List
images[0] = 'simpleslideshow/slide1.jpg';
images[1] = 'simpleslideshow/slide2.jpg';
images[2] = 'simpleslideshow/slide3.jpg';
images[3] = 'simpleslideshow/slide4.jpg';
// Change Image
function changeImg(){
document.slide.src = images[i];
if(i < images.length - 1){
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
I want to implement sliding images as soon as the website loads.
Here's my html code
<html>
<title>Wold of Guitars</title>
<body onload="images()">
</body>
</html>
And here's my javascript
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '../img/n/h1.jpg';
imgArray[1] = new Image();
imgArray[1].src = '../img/n/h2.jpg';
imgArray[2] = new Image();
imgArray[2].src = '../img/n/home.jpg';
imgArray[3] = new Image();
imgArray[3].src = '../img/n/h3.jpg';
imgArray[4] = new Image();
imgArray[4].src = '../img/n/h4.jpg';
x=-1;
function images()
{ x=x+1
if(x>4)
x=1
document.write("<li><img src='" + imgArray[x] + "' width="1350" height="630"/><span>" + imgArray[] + "</span></li>");
var t=setInterval("images()",3000);
}
Help will be appreciated.
Although you mentioned "sliding" your initial code looked liked you wanted to swap the images over time.
I admit you may struggle to find good resources on JavaScript for something so simple, which Is why I can relate to your question.
Ok so here's a quick & dirty but more modern-ish image changing slide requestAnimationFrame:
https://jsfiddle.net/julienetienne/95tqftnk/4/
The same principals apply for making images slide except you are pre-loading all images and shifting the position by the slide show width.
var speed = 3;
// Your image array
var images = [
'http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg',
'http://www.hdwallpapersimages.com/wp-content/uploads/images/Child-Girl-with-Sunflowers-Images.jpg',
'http://www.gettyimages.co.uk/CMS/StaticContent/1391099215267_hero2.jpg'];
// Get the slideShow tag
var slideShow = document.getElementById('slide-show');
// Create the image tag //You could also just make one in HTML and get the tag
var img = document.createElement('img');
// Append the image to the slideshow container
slideShow.appendChild(img);
// Basic request animation polyfill
var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
return setTimeout(callback, 1000 / 60);
};
// declare var count outside of rAF loop
var count;
function changeImage(timeStamp) {
count = Math.floor(timeStamp / 1000 / speed);
while (count > images.length -1) {
count -= images.length;
}
img.src = images[count];
rAF(changeImage);
}
rAF(changeImage);
img {
width: 600px;
height auto;
}
<div id="slide-show"></div>
I created site with changing background images.
HTML:
<div id="templatemo_header">
</div>
CSS:
#templatemo_header {
background: url(images/templatemo_header.jpg) no-repeat;
}
And JS code which changes the BG image each 3 seconds
function displayImage(image) {
document.getElementById("templatemo_header").style.backgroundImage = image;
}
function displayNextImage() {
x = (x == images.length - 1) ? 0 : x + 1;
displayImage(images[x]);
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
displayImage(images[x]);
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = 'url("images/templatemo_header1.jpg")';
images[1] = 'url("images/templatemo_header2.jpg")';
images[2] = 'url("images/templatemo_header3.jpg")';
images[3] = 'url("images/templatemo_header.jpg")';
The problem is when each of BG images changed only first time, image dissapeares and after some moment new image appears.
I guess, it's because new BG image is downloaded.
Is it some way to force download the images immediately, say in function startTimer?
Thanks in advance.
There are a few ways to pre-load images using javascript here. By pre-loading the images you may have better luck when displaying them. In your case I would use Method 3 if possible, if not Method 2. As described in the article, you would use the window.onload event to kick off the downloading of the images once the page has loaded.
I would just setup your image array as follows:
window.onload = preLoadImages();
function preLoadImages(){
preLoadImage = new Image();
images[0] = "images/templatemo_header1.jpg";
images[1] = "images/templatemo_header2.jpg";
images[2] = "images/templatemo_header3.jpg";
images[3] = "images/templatemo_header.jpg";
for(i=0, i<=images.length, i++){
preLoadImage.src=images[i];
}
}
I had problem with event listener and image loader in my code. When i try to load and check status of loaded image based on event listener some of images skipped. I think browser can handle only one event and when active one isn't stopped next can work and skip its work. So few of images return wront status and can be used. Just give me some advices about this. Here is my code:
//Image loader
var urlList = [
'images/ground_02.png', // 0 - FG
'images/ground_layer0.png', // 1 - CITY
...
];
var urlListLength = urlList.length; //length of URL-array
var iCount = new Number(0); // Create zero-counter
var images = new Array(); // All images array. Each elem stores one image
var imageInfo = function(imageName, imageCount, imageWidth, imageHeight) { // Constructor for image data container
this.imageName = imageName; // Url of image
this.imageCount = imageCount; // Frames
this.imageWidth = imageWidth; // Width of images
this.imageHeight = imageHeight; // Height of images
};
var imageData = new Array(); // Images data array
for (var i=0; i!=urlListLength; ++i) { // Loop for each image load
images[i] = new Image(); // Image array.
images[i].addEventListener('load', function(i) {
imageData.push(new imageInfo(images[iCount], images[iCount].width/images[iCount].height, images[iCount].width, images[iCount].height));
iCount++;
if (iCount == urlListLength) {
var loaded = true;
loop();
};
}, false);
images[i].src = urlList[i];
images[i].onerror=function() {
alert("FAIL "+this.src);
};
};
You have a problem at least here:
imageData.push(new imageInfo(images[iCount], images[iCount].width/images[iCount].height, images[iCount].width, images[iCount].height));
load event is fired once image is loaded by browser. But it is not necessary that it will be fired in the same order as load is started. Basically, images[2] could be loaded before images[0] and images[1] and in that case iCount won't work.
You can use this instead of images[iCount] as in this case this will point to exact that image which has fired load event.
imageData.push(new imageInfo(this, this.width/this.height, this.width, this.height));
I think browser can handle only one event and when active one isn't
stopped next can work and skip its work.
Nope. That is wrong. Regularly all events will be fired. But JS is single threaded, so it will simply put an event into a queue and will run next event after previous is done. It will not skip any event.
This should work for all browsers, including IE6.
var list = [
'images/ground_02.png',
'images/ground_layer0.png'
],
images = {};
function loadImage() {
images[this.src] = {
loaded: (this.width > 0 ? true : false),
src: this.src,
width: this.width,
height: this.height
};
if (list.length < 1) return;
var url = list.pop(),
img = new Image();
img.onload = loadImage;
img.onerror = loadImage;
img.src = url;
}
loadImage(); // Initialize loading
And if you need to check if an image has been loaded:
function isImageLoaded(src) {
return (images[src] && images[src].loaded);
}
if (isImageLoaded('images/ground_02.png')) alert('Yes!');