Skip to content

Commit 80def90

Browse files
committed
Allow for the URL to be passed in Opts
Lets a user pass in an option of url on an element. Updated the readme to reflect this change.
1 parent d6c1048 commit 80def90

File tree

2 files changed

+62
-79
lines changed

2 files changed

+62
-79
lines changed

README.md

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,34 +5,34 @@ Plugin for jQuery that allows for the easy caching of image files in the browser
55
## Using the Plugin
66
The plugin can be used two ways. It can either be applied to a specific element in the DOM, or you can apply it to a container that will have images within it. Both approached will bind the Cache Image plugin to all future changes that occur to those elements or their children.
77

8+
**Options**
9+
Each of these is optional.
10+
11+
* *debug*: Enables a lot of console messaging to help you troubleshoot [default: false]
12+
* *defaultImage*: URL or base64 string for the default image (will obviously get cached) - default is at assets/default.jpg
13+
* *encodeOnCanvas*: Experimental use of the HTML5 canvas element to encode the images | Not recommended for production [default: false]
14+
* *storagePrefix*: Used to prefix the URL in the localStorage key [default: 'cached']
15+
* *url*: Set the image URL to be cached for the selector [default: null]
16+
817
### Attaching to an Element
9-
`$('img#AnElement').cacheImage();`
18+
`$('img#AnElement').cacheImages();`
1019
Any selector here works, however it will bind to only existing elements. If you need to have the caching work on future dynamically created elements use the second approach.
1120

12-
### Attached to a Parent Container
13-
`$('div#AwesomeContainer').cacheImage();`
21+
### Attached to a Parent Container *Coming Soon*
22+
`$('div#AwesomeContainer').cacheImages();`
1423
This will watch for changes to the parent and all child elements for changes that involve images. The plugin will step in, cache the image into local storage, and reveil the image to the user.
24+
25+
### Dynamically Adding an Element
26+
`$('img').cacheImages({url: 'http://upload.wikimedia.org/wikipedia/commons/1/1d/Fishfinger1.jpg'};`
27+
Allows you to easily drop caching into your dom additions. It will look at the cached files, and if none exist, it will insert the default image, and attempt to fetch the specified image.
1528

1629
### Manually caching an image
17-
`cacheImageFetchURL('http://yourenota.plumber/wear-a-belt.png');`
30+
`cacheImageFetchURL('http://upload.wikimedia.org/wikipedia/commons/9/92/Muraltmuur.jpg');`
31+
1832
Attempts to cache that image into your clients browser local storage. This can be very helpful if you have an app where you are storying data into webSQL or IndexedDB and want to grab images during an initial sync, but those images might not be needed until later. By caching the images earily you ensure that they would be available along with the other data.
1933

2034
These images would later be automatically placed due to element or parent binding, or you could manually place them (see below).
2135

22-
## Configuring the plugin
23-
There are no required configuration steps for the plugin to work (aside from actually calling the function at least once). You are able to
24-
25-
## Future Goals
26-
I would love to see this also apply to background images. Currently you can manually cache the image, and the manually display the image into your css. It would look like the following.
27-
28-
1. Caching the Image if used before hand
29-
1. Use the place image function
30-
31-
```
32-
cacheImageFetchURL('http://lookatmy.diamonds/mega-stone.jpg'); // Use to pre-cache earlier
33-
cacheImageDisplay('http://lookatmy.diamonds/mega-stone.jpg'); // Use to insert the base64 encoded image string
34-
```
35-
3636
# Credits and Thanks
3737
* Based Heavily off of @doomhz plugin [jQueryImageCache](https://github.com/doomhz/jQuery-Image-Cache)
3838
* Utilizing base64 encoding from @mathias [Encoding XHR image data](http://jsperf.com/encoding-xhr-image-data/33)

jquery.cacheImages.js

Lines changed: 44 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,13 @@
2222
window.cacheImagesConfig = $.extend({}, {
2323
debug: true, // Boolean value to enable or disable some of the console messaging for trouble shooting
2424
defaultImage: 'data:image/png;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAHgAA/+4ADkFkb2JlAGTAAAAAAf/bAIQAEAsLCwwLEAwMEBcPDQ8XGxQQEBQbHxcXFxcXHx4XGhoaGhceHiMlJyUjHi8vMzMvL0BAQEBAQEBAQEBAQEBAQAERDw8RExEVEhIVFBEUERQaFBYWFBomGhocGhomMCMeHh4eIzArLicnJy4rNTUwMDU1QEA/QEBAQEBAQEBAQEBA/8AAEQgAZABkAwEiAAIRAQMRAf/EAEsAAQEAAAAAAAAAAAAAAAAAAAAFAQEAAAAAAAAAAAAAAAAAAAAAEAEAAAAAAAAAAAAAAAAAAAAAEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//2Q==', // URL or base64 string for the default image (will obviously get cached) - default is at assets/default.jpg
25-
storagePrefix: 'cached' // Used to prefix the URL in at localStorage key
25+
encodeOnCanvas: false, // This is still experimental and should be disabled in production
26+
storagePrefix: 'cached', // Used to prefix the URL in at localStorage key
27+
url: null // Allows you to directly set the url for an element
2628
}, opts);
2729

2830
// Check for canvas support
29-
window.cacheImagesConfig.canvasEncoder = typeof HTMLCanvasElement != undefined ? window.cacheImagesConfig.canvasEncoder : false;
31+
window.cacheImagesConfig.encodeOnCanvas = typeof HTMLCanvasElement != undefined ? window.cacheImagesConfig.encodeOnCanvas : false;
3032

3133
var self = this;
3234

@@ -36,22 +38,22 @@
3638
* filename | string | this is the url accessed/filename, it's needed so that we can parse out the type of image for mimetyping
3739
* Code base heavily on Encoding XHR image data by @mathias - http://jsperf.com/encoding-xhr-image-data/33
3840
*/
39-
var getBase64Image = function( img ){
41+
var base64EncodeCanvas = function( img ){
4042
try {
41-
var canvas = document.createElement('canvas'),
42-
imgType = img.src.match(/\.(jpg|jpeg|png)$/i);
43+
var canvas = document.createElement('canvas');
4344
canvas.width = img.width;
4445
canvas.height = img.height;
4546

46-
if (imgType && imgType.length) {
47+
var ctx = canvas.getContext('2d');
48+
ctx.drawImage(img, 0, 0);
49+
50+
var imgType = img.src.match(/\.(jpg|jpeg|png)$/i);
51+
if( imgType && imgType.length ) {
4752
imgType = imgType[1].toLowerCase() == 'jpg' ? 'jpeg' : imgType[1].toLowerCase();
4853
} else {
4954
throw 'Invalid image type for canvas encoder: ' + img.src;
5055
}
5156

52-
var ctx = canvas.getContext('2d');
53-
ctx.drawImage(img, 0, 0);
54-
5557
return canvas.toDataURL('image/' + imgType);
5658
} catch (e) {
5759
console && console.log(e);
@@ -107,46 +109,58 @@
107109
return base64;
108110
};
109111

110-
$(document).ready(function () {
112+
/*
113+
* Here is the magic, this is the function that processes through the caching of the images
114+
*/
115+
$(function () {
111116
// console.log( $(self) );
112117
$(self).each(function (i, img) {
113118
var $this = $(img),
114-
src = $this.prop('src') || $this.data('cachedImageSrc'),
115-
key = window.cacheImagesConfig.storagePrefix + ':' + src, // Prepare the localStorage key
119+
src = $this.prop('src') || $this.data('cachedImageSrc');
120+
if( window.cacheImagesConfig.url !== null ){ // URL set in the opts
121+
src = window.cacheImagesConfig.url;
122+
$this.prop('src', '');
123+
}
124+
125+
var key = window.cacheImagesConfig.storagePrefix + ':' + src, // Prepare the localStorage key
116126
localSrcEncoded = localStorage[key];
117127

118128
if( typeof localStorage !== "object" ){ // See if local storage is working
119129
if( window.cacheImagesConfig.debug ){ console.log("localStorage is not available"); }
120-
return false;
130+
return false; // Unable to cache, so stop looping
121131
}
122132

123-
if( typeof src === 'undefined' ){ return false; }
124-
125-
// Check if we need to
133+
if( typeof src === 'undefined' ){ return true; } // Move to the next item
134+
if( typeof $this.prop('src') !== 'undefined' && $this.prop('src').substring(0,5) === 'data:' ){ return true; } // This has already been converted
126135

127-
window.cacheImagesConfig.canvasEncoder = typeof HTMLCanvasElement != undefined ? true : false;
136+
128137

129-
if( src.substring(0,5) === 'data:' ){ return true; } // This has already been converted
130138
if( localSrcEncoded && /^data:image/.test( localSrcEncoded ) ) {
131139
// Check if the image has already been cached, if it has lets bounce out of here
140+
$this.data('cachedImageSrc', src);
132141
$this.prop('src', localSrcEncoded);
133142
}else{
134143
// The image has not yet been cached, so we need to get on that.
135144
$this.prop('src', src);
136145
var imgType = src.match(/\.(jpg|jpeg|png|gif)$/i); // Break out the filename to get the type
137-
if (imgType && imgType.length){ // Get us the type of file
146+
if( imgType && imgType.length){ // Get us the type of file
138147
imgType = imgType[1].toLowerCase() == 'jpg' ? 'jpeg' : imgType[1].toLowerCase();
139148
}
149+
if( typeof imgType === 'undefined' ){ return true; }
150+
140151

141152
if( localStorage[key] !== 'pending' ){
142153
localStorage[key] = 'pending';
154+
$this.data('cachedImageSrc', src);
143155

144-
window.cacheImagesConfig.canvasEncoder = typeof HTMLCanvasElement != undefined ? true : false;
145-
if( window.cacheImagesConfig.canvasEncoder && imgType !== 'gif' ){
156+
if( window.cacheImagesConfig.encodeOnCanvas && imgType !== 'gif' ){
146157
$this.load(function () {
147-
localStorage[key] = getBase64Image(img);
158+
localStorage[key] = src = base64EncodeCanvas( img );
148159
if( src.substring(0,5) === 'data:' ){
149160
$this.prop('src', localStorage[key] );
161+
if( $this.data('cacheImagesRemove') === 'true' ){
162+
$this.remove();
163+
}
150164
}
151165
});
152166
}else{
@@ -156,60 +170,29 @@
156170
xhr.onload = function( e ) {
157171
if (this.status == 200){
158172
localStorage[key] = 'data:image/' + imgType + ';base64,' + base64EncodeResponse( this.response );
173+
$this.prop('src', localStorage[key] );
174+
if( $this.data('cacheImagesRemove') === 'true' ){
175+
$this.remove();
176+
}
159177
}else{
160178
localStorage[key] = 'error';
161179
}
162180
};
163181
xhr.send();
164-
}
182+
}
165183
}
166184
}
167185
});
168186
});
169-
187+
170188
return this;
171189
};
172-
/*
173-
* Will place the cached image into the element.
174-
*/
175-
window.cacheImagesDisplay = function( elem, src ){
176-
console.log(elem);
177-
console.log(src);
178-
if( typeof elem !== "object" && typeof elem.context.tagName !== 'undefined'){ // Ensure that the element a valid DOM element
179-
if( window.cacheImagesConfig.debug ){ console.log('The elem variable passed was not valid'); }
180-
return false;
181-
}
182-
if( typeof localStorage !== "object" ){
183-
if( window.cacheImagesConfig.debug ){console.log("localStorage is not available"); }
184-
return false;
185-
}
186-
187-
if( typeof src === 'undefined' ){
188-
if( typeof elem.prop('src') === 'string' ){
189-
src = elem.prop('src'); // use the elements SRC as the source
190-
}else{
191-
if( window.cacheImagesConfig.debug ){ console.log('No source to fetch'); }
192-
return false;
193-
}
194-
}
195-
196-
// Check if it has already been cached
197-
var key = window.cacheImagesConfig.storagePrefix + ':' + src;
198-
if( src.substring(0,5) === 'data:' ){ return elem; } // This has already been converted
199-
200-
//
201-
// Lets cache it up
202-
var resposne = cacheImagesFetchURL( src );
203-
204-
205-
return elem;
206-
},
207190
/*
208191
* Manually cache an image into the local storage
209192
*/
210193
window.cacheImageFetchURL = function( url ){
211-
$('body').append($('<img style="display: none;" />').prop('src', url ).cacheImages() );
212-
},
194+
$('body').append($('<img style="display: none;" />').prop('src', url ).data('cacheImagesRemove', 'true').cacheImages());
195+
};
213196
/*
214197
* Will remove all of the cached images from their localStorage
215198
*/

0 commit comments

Comments
 (0)