3

这篇文章的标题读作 webdev-hipster 就像一场野猫比赛中的紧身法兰绒围巾。对不起。

我对脚本运行时优化不是很好,所以我想知道下面的函数调用在计算上会有多糟糕。我知道这对于大型站点来说并不实用,但是在我想使用它的地方,jQuery 调用将返回不超过六个对象,所以音量并不高。

 Modernizr.load({
    test: Modernizr.borderradius && Modernizr.boxshadow,
    nope: "_/js/polyfills/pie.js",
    complete: function(){
        if(window.PIE){
            $('*').css('box-shadow').each(function(){ PIE.attach(this); });
            $('*').css('border-radius').each(function(){ PIE.attach(this); });
        }
    }
 });

谢谢大家。

4

2 回答 2

1

试试这个。

 Modernizr.load({
    test: Modernizr.borderradius && Modernizr.boxshadow,
    nope: "_/js/polyfills/pie.js",
    complete: function(){
        if(window.PIE){
            $('*').each(function(){
                var $this = $(this);
                //check if box-shadow or border-radius is applied
                if($this.css('box-shadow') || $this.css('border-radius')){
                    PIE.attach(this);
                }
            });
        }
    }
 });
于 2012-02-15T19:35:41.693 回答
0

... jQuery 调用将返回不超过六个对象...

所以半打是六。其中四个将是htmlheadscriptbody。:-) 页面上只有两个其他元素?

说真的,如果这个数字非常低,那也没关系。但是,您希望将$()调用限制在真正需要它的元素上,而不是$("*")大锤子。

如果您确实需要遍历整个文档,请使用简单的递归下降函数:

function applyPie(element) {
    var node;
    for (node = element.firstChild; node; node = node.nextSibling) {
        if (node.nodeType === 1) { // 1 = element
            node.style.boxShadow = /* ...?... there's nothing in your jQuery call */;
            node.style.borderRadius = /* ...?... there's nothing in your jQuery call */;
            PIE.attach(node);
            applyPie(node);
        }
    }
}

applyPie(document.documentElement);

这需要PIE.attachdocumentElement. 您可以使用nodeName(或tagName),这样您就不会将 PIE 附加到 htmlheadstyle等。使用简单的递归下降函数可以避免在内存中创建大型平面数组,这就是这样$("*")做的。

于 2012-02-15T18:13:43.840 回答