JQuery插件为<img/>的分区域名着色

时间:2011-11-01 22:27:57

标签: javascript jquery performance optimization jquery-plugins

我正在阅读Stoyan Stefanov的excellent article about JS domain sharding图像文件,并希望改进他的食谱。

以下脚本将遍历页面中的图像,根据“src”值的长度将每个图像分配给一个存储桶,并将其分配给存储桶(将其记录到控制台)。

我要做的是创建一个JQuery插件,可以接受像$('img')或$('link')这样的集合,并用像http:/的分片域重写“src”属性/images1.mydomain.com/path/to/image.png”。

如果我的页面有:

<img src="/Images/file1.png" />
<img src="/Images/filenumber2.png" />
<img src="/Images/footer.png" />

我想做类似的事情:

$(document).ready(function(){
  $('img').domainShard(3, "subdomain", "mydomain.com")
});

大致生产:

<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" />

使用像这样的JQuery插件:

(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);

这是Stoyan的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));

当我有工作的时候,我会继续乱砍并报告 - 非常感谢任何建议或帮助。

谢谢!

2 个答案:

答案 0 :(得分:1)

$(document).ready(function () {
            $("img").domainShared("striano.net", "images", true);
        });

        $.fn.domainShared = function (topDomain, subDomain, useSSL) {
            return this.each(function () {
                var _this = $(this)
                if (useSSL) {
                    _this.attr("src", "https://" + subDomain + "." + topDomain + _this.attr("src"));
                } else {
                    _this.attr("src", "http://" + subDomain + "." + topDomain + _this.attr("src"));
                }
            });
        }

答案 1 :(得分:0)

您可以尝试使用协议相关:

_this.attr("src", "//" + subDomain + "." + topDomain + _this.attr("src"));