I was reading Stoyan Stefanov’s excellent article about JS domain sharding for image files and wanted to improve his recipe.
The below script will iterate through the images in a page, assign each to a bucket based on the length of the “src” value, and assign it to a bucket (logging this to the console).
What I’m trying to do is create a JQuery plugin that can accept a collection like $(‘img’) or $(‘link’) and rewrite the “src” attribute with a sharded domain like “http://images1.mydomain.com/path/to/image.png”.
If my page has:
<img src="/Images/file1.png" />
<img src="/Images/filenumber2.png" />
<img src="/Images/footer.png" />
I want to do something like:
$(document).ready(function(){
$('img').domainShard(3, "subdomain", "mydomain.com")
});
To roughly produce:
<img src="http://subdomain1.mydomain.com/Images/file1.png" />
<img src="http://subdomain2.mydomain.com/Images/filenumber2.png" />
<img src="http://subdomain3.mydomain.com/Images/footer.png" />
Using a JQuery plugin like so:
(function ($) {
$.fn.domainShard = function (buckets, subdomain, domain) {
var numBuckets = buckets || 3;
var subdomain = subdomain || "images";
var domain = domain || "mydomain.com";
return this.each(function () {
// look at the src
// var src = $(this).attr('src');
// compute bucket assignment
// do stuff
// set the new path
// newSrc = $(this).attr('src', path);
});
};
})(jQuery);
Here is Stoyan’s Javascript:
function getBucket(url, numbuckets) {
var number = url.length,
group = number % numbuckets;
return group;
}
function toBuckets(stuff, numbuckets) {
var numbuckets = parseInt(numbuckets, 10),
url, group,
buckets = Array(numbuckets),
cache = {};
for (var i = 0, max = stuff.length; i < max; i++) {
url = stuff[i].src;
if (typeof cache[url] === 'number') {
continue;
}
group = getBucket(url, numbuckets);
if (!buckets[group]) {
buckets[group] = [];
}
buckets[group].push(url);
cache[url] = group;
}
return buckets;
}
console.log(toBuckets(document.images, 3));
I’ll keep hacking away and report back when I have something working — any advice or assistance is greatly appreciated.
Thanks!
1 Answer