Is this the right way to preload images? - javascript

Is this below the right way to preload images?
I have a table which changes background once a 'select option' is changed.
In the body of my page, I have this:
<body onload="preload();">
And in my Form on the same page I have:
<select onchange="swap();"><option bla bla></select>
And the js:
function preload(){
pic = new image(720, 65);
pic.src = '../picture.jpg';
}
function swap(){
document.getElementById("table_id_here").style.backgroundImage = '../picture.jpg';
}
In the function swap() I guess the picture.jpg file is already preloaded, is that right?
Is there any way to check if the image has actually been cached (preloaded)?

Load the image with CSS either by using a sprite or by using display:none to hide it. A bit less to do on the js front then.

Use something like Firebug's network tool to check if those images are loaded.
(source: getfirebug.com)
I guess your codes should work, anyway this is a popular script used by Dreamweaver for image preloading:
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
MM_preloadImages('img1.gif','img2.gif'); //add more if required

The word "image" should be capitalized in the second line of your preload function, like this:
pic = new Image(720, 65);
Remember that you're creating a new Image object by calling its constructor -- that's what loads it in the browser.
So if it's not capitalized, you're invoking a separate function that may or may not exist.

Related

adding Picture dynamically to Photoswipe

I am trying to add pictures(from an array) dynamically to photoswipe. I have tried to use the "append" Method of jquery without a success.I also readed all about what people wrote about this issue on the web but i did not find the rigth answer.Any helps are welcome.
I found a way to add images dynamically to photoswipe, but it is a bit hackish.
There are 3 tings one must do:
Update the originalImages (dont know how importent this is).
Add click handlers to all images.
Add all images to the instance.cache.images.
I did this with the following code:
var images, image, i, metaData, src,caption,
Util =window.Code.Util;
images=$('#addedImages').find('a');
instance.originalImages = $('#all-photo-swipe-images').find('.a');
for (i = 0; i < images.length; i++) {
image = images[i];
src = instance.settings.getImageSource(image);
caption = instance.settings.getImageCaption(image);
metaData = instance.settings.getImageMetaData(image);
image.__photoSwipeClickHandler = PhotoSwipe.onTriggerElementClick.bind(instance);
Util.Events.remove(image, 'click', image.__photoSwipeClickHandler);
Util.Events.add(image, 'click', image.__photoSwipeClickHandler);
image = new PhotoSwipe.Image.ImageClass(image, src, caption, metaData);
instance.cache.images.push(image);

Rendering custom photo set using tumblr JSON

I am creating this custom theme www.designislikethis.tumblr.com, which uses the jQuery Masonry and the Slider plugins. In creating this theme I wanted to create my own photoset slideshow instead of messing around with the default Flash-based one.
I started by pulling the images from the JSON of each photoset post by the post's ID using JS and jQuery.
I then rendered these images onto my frontpage in a special div that is linked to a minimal jQuery slideshow plugin, so each image fades in and out.
The code I use to pull/render for each photoset post is as follows:
function photoSet() {
$('.photoset').each(function () {
var postID = $(this).attr('id');
var that = $(this);
$.getJSON("http://designislikethis.tumblr.com/api/read/json?id="+postID+"&callback=?",
function(data) {
var postPhotos = data["posts"][0]["photos"];
var postPermalink = data["posts"][0];
for(var i = 0; i<postPhotos.length; i++)
{
var photo250 = new Image();
photo250.src = postPhotos[i]['photo-url-250'];
postLink = postPermalink["url-with-slug"];
var setClass = ".photoset"+ i;
var imgClass = ".img"+ i;
$(that).find('.slide').append('<a class="'+ setClass +'" href="'+postLink+'"><img class="'+ imgClass +'" src="' +photo250.src+ '"/></a>');
}
});
});
}
Now my problem lies in that all the other elements on my tumblr index page are not rendered with JSON, so they load faster. By the time my photo set renders it's divs are unproportional to everything that has loaded around it, and so the image slider wont kick in and you are left with a mess of rendered images.
What's most annoying about this problem is that some times it works fine, and others it's a mess, depending on how fast the page loads, or if you have the website already cached in your browser.
To see the extent of my Javascript and how I am calling this photoset funciton see here:
http://helloauan.com/apps/DILTtheme/utils.js
I know it's a little messy, for I am new to all of this. :)
Thanks.
I don't know if it will help, but you could try the following:
If the images are the same size and you know that size set the ".slide" div to that;
Try preloading the images and only starting the slide show when they are loaded. e.g using a preload plug-in.
and making use of the "callback" function.

How to use JS to trigger a GIF animation?

I have an animated GIF that plays once (doesn't loop). I would like it to animate when clicked.
I tried something like this:
$('#plus').click(function(){
$('#plus').attr('src','');
$('#plus').attr('src','img/plus.gif')
});
With the hope that quickly resetting the src would trigger the animation, but no luck. Anyone know what would do it?
Try adding the image with a randomly generated querystring so it looks like a new image to the browser.
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
$('#plus').click(function(){
$('#plus').attr('src','img/plus.gif?x=' + randomString())
});
</script>
function refreshSrc(who){
return who.src= who.src.split('?')[0]+'?='+(+new Date());
}
refreshSrc(document.images[0])
Tart it up with jQuery syntax, if you like.
This is a bit of an alternative approach.
You could export the individual frames as their own images and handle animation via javascript.
It lets you do a couple of cool things. A colleague recently had a little timer animation that was synced to the configurable slideshow interval in our image gallery.
The other thing you get out of this is you could use pngs and have translucent backgrounds.
There's probably a sprite animation library for javascript out there somewhere :)
Have you tried removing the img tag and adding it back again? (never tried it, just an idea)
You could try having a single-frame image (of the first frame of animation) and show/hide each one on click. If you want it to reset back to the single-frame image when the animation is done, you could use setTimeout (with how long the animation is as the length of time) and have it hide the animation and show the static image.
For those who want to do this when it scrolls into view i did the following.
Link for appear.js : https://github.com/morr/jquery.appear
$('img.large-magnify-glass-animation').appear(function() {
$(this).delay(200, function(){
$(this).attr('src','http://example.com/path/to/gif.gif');
});
});
I just loaded the same gif via the attr('src') upon visiblity after a short delay. No timestamp or random char function. Just used appear plugin.

how to preload large size image?

i have certain links, on mouse over of those links I am changing <div> background image
jQuery I have used is-
function imgchange()
{
$('.smenu li').mouseover( function(){
var src = $(this).find('a').attr('href');
$('.hbg').css('background-image', 'url(' + src + ')');
$(this).find('hbg').attr('title', 'my tootip info');
});
}
It is working fine but the problem is when I running it on server images takes 3-4 sec to be changed on change, but the second time I do mouse over images are getting changed instantly, I think this is because of browser stored images in cache. So I added one javascript to preload images on page onLoad() ivent -
<script language = "JavaScript">
function preloader()
{
heavyImage = new Image();
heavyImage.src = "images/soluinfo1.jpg";
heavyImage.src = "images/soluinfo2.jpg";
heavyImage.src = "images/soluinfo3.jpg";
heavyImage.src = "images/soluinfo4.jpg";
heavyImage.src = "images/soluinfo5.jpg";
heavyImage.src = "images/soluinfo6.jpg";
heavyImage.src = "images/soluinfo7.jpg";
}
</script>
<body onLoad="javascript:preloader()">
but this script has not solved my problem.what should I do?
#Richard's answer (sprites) is probably the best one for what you are after, but the reason your code is not working is that in most browsers, only the last heavyImage.src="" is given enough time to actually register with the browser as an actual request. You're creating only one Image object setting and resetting the .src attribute faster than the browser can request the files (I think modern JavaScript engines take the added step of removing all the intermediate .src statements specifically because of this).
There are a couple of ways to fix this. The easiest is to create multiple Image objects, one for each image. And the easiest way to do that is through something like this:
<script type="text/javascript">
function preloader()
{
function doPreload(strImagePath)
{
var heavyImage = new Image();
heavyImage.src = strImagePath;
}
var arrImages = ["images/soluinfo1.jpg","images/soluinfo2.jpg","images/soluinfo3.jpg","images/soluinfo4.jpg","images/soluinfo5.jpg","images/soluinfo6.jpg","images/soluinfo7.jpg"];
for (var i = 0; i < arrImages.length; i++) {
doPreload(arrImages[i]);
}
}
</script>
By putting the heavyImage variable inside its own function (remember to use the var keyword), you're ensuring that the Image object exists inside its own dedicated scope.
Another way to do this is to attach a "load" event listener to a single heavyImage. Every time the image finishes loading, go fetch the next image. The disadvantage to this method is that your images will be loaded one at a time (bad for navigation images, but great for, say, and image gallery), whereas the first technique will fetch the images in parallel (typicallly four at a time).
You might find it easier to change your approach and use CSS sprites (and another article). Then you would just have one image referenced, and you use CSS to set which part of that image gets shown in which scenario.
This assumes that the images you're using are under your control and you can use an image editor to combine them into one large image.

Preloading img elements

I currently have a preloading image javascript script:
function MM_preloadImages() {
var d = document;
if(d.images){
if(!d.MM_p )
d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
for(i=0; i<a.length; i++){
if (a[i].indexOf("#")!=0){
d.MM_p[j]=new Image;
d.MM_p[j++].src= '/img' + a[i];
}
}
}
}
The problem is that i have to manually update the array when images are added deleted etc.
Is there anyway of automating this or is there a library.
Most of the image urls are element hrefs.
Obviously I could write something server side but I want to check if there is something out there already.
Here is someone who did what you are trying to do with jQuery:
http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/
Edit: Actually this is not quite what you are looking for as this preloads images from CSS files - I am going to leave this here in case this is still helpful.
The trouble is by the time the elements are available in the DOM for JS to inspect the images are already being loaded anyway.
AFAIK there is no way to do this (the CSS based inspection works because that's loaded before the body content), but a superior solution for the problem in general is CSS spriting.

Categories