I have a standard webpage developed in php using CSS and currently a bit of javascript to cycle through some images for a offers div. You can see the site here, this will not be it's final resting place this is a temporary site. If you look at the offers banner. When it switches to the next image it goes white whilst it loads the next image. Is there anyway of loading the next image before applying it to the div background property?
Here is my javascript atm.
var c=0
var s
function offersCycle()
{
if (c%3==0){
document.getElementById('offers').style.background = "url(/images/1.jpg)";
}
if (c%3==1){
document.getElementById('offers').style.background = "url(/images/2.jpg)";
}
if (c%3==2){
document.getElementById('offers').style.background = "url(/images/3.jpg)";
}
c=c+1
s=setTimeout("offersCycle()",8000)
I tried using a set of new Images in the javascript and defining them before cycling them but they wouldn't apply to the CSS as this relies on a url and not an image itself? Any ideas appreciated.
Cheers,
Jordan
I would do something like this:
var c = 0, images = ["/images/1.jpg", "/images/2.jpg", "/images/3.jpg"];
for(var i=0; i<images.length; i++) {
var img = new Image();
img.src = images[i];
}
function offersCycle() {
document.getElementById('offers').style.background = "url("+images[c%images.length]+")";
c++;
}
var s = setTimeout(offersCycle, 8000);
By using an array, we simplify the logic and can use the same array to preload the images to cache them when the page first loads. This also allows you to add as many images as you want to the array without changing anything.
You could preload the images using Javascript.
Details here: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5214317.html
Related
I need some suggestion on how to work this around.
I have an Ajax code to execute when the LInk is clicked in my page. The ajax code is to call the PHP code to query the images(thumbnail size) filename inside a certain directory. Once executed, the ajax data will have the filenames of my thumbnails in that directory and display the thumbnails in my page dynamically.
I want to know any suggestion how to check if all thumbnails are already finished loading without using the SetTimeOut()? and execute some jquery codes once all thumbnails are loaded. I need my thumbnails to be loaded so I can set the size of my thumbnails div for scrolling.
Method:
function imagesLoaded(imgAr, callback){
var
// This is a copy of the array of images
imageAr = imgAr.slice(0),
// This holds the javascript Image Objects
images = [],
// This is the number of Images that has loaded
loadedCount = 0;
var imageLoaded = function(){
// An image has finished loading, so increment the number of images loaded by 1
loadedCount++;
if(loadedCount>=imageAr.length){
// If all images have finished loading, run the 'callback' function, to report back that images have all loaded
callback.call();
}
}
// Loop around each image url
for(var i=0;i<imageAr.length;i++){
// For each image, create a new object
images[i] = new Image();
// when the image finishes loading, call the imageLoaded function
images[i].onload = imageLoaded;
// Assign the image the appropriate src attribute
images[i].src = imageAr[i];
}
}
Use:
var imageAr = ['a.jpg', 'b.jpg', 'c.jpg'];
imagesLoaded(imageAr, function(){
alert('Images loaded!');
});
You could use load method for the images, like:
$('someElement img').load(function(){
//all loaded
});
Did you mean something like that
I am using the following script to display big images on mouse over the small images (example photo attached in the last). I want to show the 'loading' image (like this) while the big image is being downloaded from the server. How can this be achieved?
Note: I have asked a similar question here but I was not successful in applying the append function to the following code. Please help.
<script type="text/javascript">
function showIt(imgsrc)
{
var holder = document.getElementById('imageshow');
var newpic= new Image();
newpic.src=imgsrc;
holder.src=imgsrc;
holder.width = newpic.width;
holder.height=newpic.height;
}
</script>
<body>
/***on hover, xyz.jpg will be replaced by bigA.jpg and so on***/
<img src="smallA.jpg" onMouseOver="showIt('bigA.jpg')"/>
<img src="smallB.jpg" onMouseOver="showIt('bigB.jpg')"/>
<img src="xyz.jpg" id="imageshow" />
</body>
Images have a load event. As long as you set the load handler before the image.src is set, you should get notified when the image has successfully loaded or encounters some kind of error in loading. I do that very thing in a slideshow that I wrote so I know when the next image is ready for display and I display a wait cursor (animated gif like you're wanting) if the image has been delayed more than one second beyond it's appointed display time so the user knows what's going on.
In general, you can do something like this:
function loadImage(url, successHandler, errorHandler) {
var myImg = new Image();
myImg.onload = myLoadHandler; // universally supported
myImg.onabort = myErrorHandler; // only supported in some browsers, but no harm in listening for it
myImg.onerror = myErrorHandler;
myImg.src = url;
function myLoadHandler() {
successHandler(myImg, url);
}
function myErrorHandler() {
if (errorHandler) {
errorHandler(url);
}
}
}
Using code like this, you can display the wait cursor when you initiate the image load and hide it when the successHandler gets called.
If there were any other listeners to these events, then you should use addEventListener or attachEvent instead of onload, onabort, onerror, but if there's only one listener, you can go either way.
If the desired images are known in advance, then it's sometimes a better user experience (less waiting) to preload images that may be used later. This gets them into the browser's memory cache so they will appear instantly when needed. One can preload images either in HTML or in JS. In HTML, just insert tags into the web page for all the desired images (but hide them with CSS). In JS, just create an image array and create the image objects:
// image URLs to preload
var preloadImageURLs = [
"http://photos.smugmug.com/935492456_5tur7-M.jpg",
"http://photos.smugmug.com/835492456_968nf-M.jpg",
"http://photos.smugmug.com/735492456_3kg86-M.jpg",
];
var preloads = []; // storage for preloaded images
function preloadImages() {
var img, i;
for (i = 0; i < preloadImageURLs.length; i++) {
img = new Image();
img.src = preloadImageURLs[i];
preloads.push(img);
}
}
This will cause all the images in the preloadImageURLs array to be preloaded and available instantly later on in the life of the web page, thus preventing any user delays while waiting for images to be loaded. Obviously, there's a short amount of time for the preloaded images to actually get loaded, but for smallish images that usually happens before the user interacts with the web page so it makes for a faster feel to dynamic parts of the web page that use images.
<img id=access src=loading.gif>
<script>
window.onload=function(){
document.getElementById('access').src='access.jpg';
}
</script>
Hope this helps.
I have some code which preloads images independent of their extension and acts in a way similar to the :hover pseudo class. My question is how can i expand this to include part of the filename in the source. What i mean is the script currently adds _over to the existing filename and leaves the extension also preloading these images. What i want is for it to add /index_files/filename_imagename_over where the imagename is the src of the image. So it already adds _over i want it to add /index_files/ which is static and /filename which changes based on the file name.
$(function() { $('#nav li a img').each(function() {
var originalSrc = this.src,
hoverSrc = originalSrc.replace(/\.(gif|png|jpe?g)$/, '_over.$1');
image = new Image();
image.src = hoverSrc;
$(this).hover(function() {
image.onload = function() {
}
this.src = hoverSrc;
}, function() {
this.src = originalSrc;
});
});
})
I am also wondering if i can include php script in my javascript, i presume i cant because the server wont process the php because it isn't a .php file.
This is the example.
If so can i use this in the script.
I suppose it would also be possible to simply use a php include() for the javascript into my php document so that the script is included at the server level and the php code is processed.
another easy solution would be to use the images as backgrounds (css) and for the hoover effect you change the background position e.g. http://www.dynamicsitesolutions.com/css/background-image-switching/
I have a javascript slider for my site, which works for all browsers except for ie7. I figured out why the images are not showing.
Im using the previous version of the Marco Folio background slider.
I would appreciate some help with this, as this seems to be the only serious issue with my site right now.
Here is the site: doctorstvnetwork.com
Thanks a lot.
I realize that this is not the answer you're looking for, but thought I'd post this anyhow.
Your slider images are loading in real-time, causing a delay in seeing the image the first time the slider switches to them. You can preload the images in the background with this snippet:
/*
* preload images function
*/
(function($) {
var cache = [];
// Arguments are image paths relative to the current page.
$.preLoadImages = function() {
var args_len = arguments.length;
for (var i = args_len; i--;) {
var cacheImage = document.createElement('img');
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
}
})(jQuery)
// call the function in doc ready
$(document).ready(function () {
$.preLoadImages("/path/to/image1.png", "/path/to/image2.png");
});
I have put together a script which is very much like the flickr photostream feature. Two thumbnails next to each other, and when you click the next or prev links the next (or previous) two images slide in. Cool!
Currently when the page loads it loads the two images. The first time nxt / prv is used then the next two images or previous two are loaded via ajax, with the id of the first image being passed in the url and the HTML for the two new images returned and displayed via ajax.
simple enough, but it got me to thinking, on a slow connection, or heavy server load then the two images, although relatively small thumbnails could still take a while to load, and the nice things with sliding panes is the fact that the hidden data slides in quickly and smoothly preferbly without a loading delay.
So I was wondering from a performance and good practice point of view which option is best, this is what I can think of for now, open to suggestions.
1, call each set of images via JSON (its supposed to be fast?)
2,load all the possible images into a json file and pull in the details that way - although browser will still have to load image. Plus sometimes there might be 4 images, other times there could be upto 1000!
3, Load 10 images via php into a Json or other file, and load all 10 images into the browser hiding the 8 which are not on show, and always showing the middle two. Problem here is that each time someone clicks, the file has to reload the first and last images, which still takes up time, although i suppose the middle images will have all been cached via the browser by now though. But still there is a loading time.
4, Is it possible to have a json image with all the image details (regardless of numbers) and use no 3 above to load 10 of those images, is it possible to use ajax to only read 10 lines and keep a pointer of the last one it read, so the json file can be loaded fast, short refresh and images either side are cached via the browser!!
Hope thats clear, any suggestions on how you would handle this?
To preload an image from Javascript, you don't need to do anything that sounds like AJAX or JSON. All you need is this:
var img = new Image();
img.src = "http://example.com/new/image.jpg";
The browser will quite happily load the image in the background, even though it's not displayed anywhere. Then, when you update the src field of another (displayed) image tag, the browser will immediately show the part of the image it's already loaded (hopefully all of it).
Fetching JSON Via Ajax will just slow you down.
You're better off using inline JSON and generated Javascript.
<?php
$images = array( "foo.jpg","bar.jpg" );
?>
<script type="text/javascript">
jQuery(function($){
var images = ( <?php echo json_encode($images); ?> );
/* Creating A Hidden box to preload the images into */
var imgbox = document.createElement("div");
$(imgbox).css({display: 'none'});
/* Possible Alternative trick */
/* $(imgbox).css({height:1px; width: 1px; overflow: hidden;}); */
$('body').append(imgbox);
$.each( images , function( ind, item )
{
#Injecting images into the bottom hidden div.
var img = document.createElement("img");
$(img).src("/some/prefix/" + item );
$(imgbox).append(img);
});
});
</script>
In the case where you want to concurrently preload a larger number of resources, a little ajax can solve the problem for you. Just make sure the caching headers are such that the browser will use the resources on the next request. In the following example, I load up to four resources concurrently.
<script>
var urls = [
"a.png",
"b.png",
"c.png",
"d.png",
"e.png",
"f.png"
];
var currentStep = 0;
function loadResources()
{
if(currentStep<urls.length){
var url = urls[currentStep];
var req = GetXmlHttpObject();
update('loading ' + url);
req.open("GET", url, true);
req.onreadystatechange = getUpdateState(req, url);
req.send(null);
} else {
window.location = 'done.htm';
}
}
function getUpdateState(req, url) {
return function() {
var state = req.readyState;
if (state != 4) { return; }
req = null;
setTimeout('loadResources()', 0);
}
}
</script>
<!-- This will queue up to four concurrent requests. Modern browsers will request up to eight images at time -->
<body onload="javascript: loadResources(); loadResources(); loadResources(); loadResources();">
Why not use text and replace the text with a picture code (works in php really nice with ajax up to 500 pictures and more)?