JavaScript创建的内联样式与JavaScript创建的样式表之间的性能差异 [英] Performance difference between JavaScript created inline styles and JavaScript created stylesheets

查看:94
本文介绍了JavaScript创建的内联样式与JavaScript创建的样式表之间的性能差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态设置DOM中给定选择器的所有元素的样式。我大概看到两种方式。对于下面的示例,我将使用 p 元素,并且它是 text-align 属性,但我对以下内容更感兴趣在我的文字对齐段落中,这是两种可能的方式的利弊。



1。内联(按元素)样式



  var个节点= document.getElementsByTagName(’p’); 
Array.prototype.forEach.call(节点,函数(节点){
node.style.textAlign = center;
});



2。样式表



  var sheet =(function(){
//创建< style>标记
var style = document.createElement( style);

// WebKit hack :(
style.appendChild(document.createTextNode());

//将< style>元素添加到页面
document.head.appendChild(style);

return style.sheet;
})();

sheet.insertRule( p {text-align:center;});

通常,我会选择内联样式的路线,因为它看起来更简单,并且可以确保样式更改会覆盖现有样式表,但是我想到其中之一:有时不覆盖样式表可能更可取,并且第二:修改一个 style 元素可能比未知数量的 p 元素更有效。



在性能方面明智的做法是,是否存在将内联样式应用于每个e的情况比创建样式表更好吗?假设答案可能取决于我正在设计的元素数量,那么创建样式表在某一点上是否会变得更有效率?



编辑:以阐明为什么我问这个问题,我将向您解释为什么要问的问题:最近,我将一些我经常复制粘贴并在项目之间适应的JS黑客变成了一组可重用的CommonJS模块。它们的作用类似于在窗口调整大小或其他触发器可能会改变最高或最高度量的情况下,将给定选择器的所有元素的高度或宽度设置为最高或最高。 >

这里是有关它的博客文章: http://davejtoews.com/blog/post/javascript-layout-hacks



以下是这些模块的GitHub存储库:





此刻t,所有这些模块都使用内联样式,但是我正在考虑将其切换为样式表。对于这两种方法的优缺点我都找不到很好的答案,所以我在这里发布了问题。

解决方案

我不知道对您的问题没有一个很好的一般性答案(我不确定是否有一个答案),但是我已经使用开发工具时间轴对您发布在Chrome 57.0.2987.98 beta上的示例进行了一些实验。






这是在单个框架中完成的工作的细目分类,更新了 10,000 < p> ; 元素(具有内联样式(左)和动态样式表(右)):









为进行比较,以下是使用 100 < p> 元素









总而言之,对于少量元素,差异可以忽略不计。对于大量元素,使用内联样式时,浏览器会花费更多时间编写脚本(这是可以预料的,因为存在大量循环)并重新计算样式(我认为这可以解释为浏览器必须每个元素解析一个样式规则,而不是一个通用样式规则。)



所有其他步骤的花费大致相同时间。特别是,使用内联样式时,绘制时间不会增加。






作为参考,我使用了以下测试页

 <!DOCTYPE html>。 
< html>
< head>
< title>< / title>
< / head>
< body>
< button id = add-stylesheet> Stylesheet< / button>
< button id = add-inline-styles> Inline< / button>
< script type = text / javascript>
let stylesheet = document.getElementById(’add-stylesheet’);
let inline = document.getElementById(’add-inline-styles’);

stylesheet.addEventListener('click',addStylesheet);
inline.addEventListener('click',addInlineStyles);

函数addStylesheet(){
let style = document.createElement( style);
style.appendChild(document.createTextNode());
document.head.appendChild(style);
style.sheet.insertRule(’p {text-align:center}’,0);
}

函数addInlineStyles(){
让节点= document.getElementsByTagName(’p’);
表示(节点的节点){
node.style.textAlign =‘center’;
}
}

//初始化< p>元素
init(10000);
函数init(numElements){
for(let i = 0; i< numElements; ++ i){
let p = document.createElement(’p’);
p.innerText =测试
document.body.appendChild(p);
}
}
< / script>
< / html>


I want to dynamically style all elements of a given selector in my DOM. I see more or less two ways about it. For the example below I'll use a p element and it's text-align attribute but I'm more interested in the pros and cons of the two possible ways of doing this than I am in specifically text-aligning paragraphs.

1. Inline (per element) Styles

var nodes = document.getElementsByTagName('p');
Array.prototype.forEach.call (nodes, function (node) {
     node.style.textAlign = "center";
});

2. Stylesheet

var sheet = (function() {
  // Create the <style> tag
  var style = document.createElement("style");

  // WebKit hack :(
  style.appendChild(document.createTextNode(""));

  // Add the <style> element to the page
  document.head.appendChild(style);

  return style.sheet;
})();

sheet.insertRule("p { text-align: center; }");

Typically I would go the route of inline styles, as it seems simpler and it ensures the style change would override the existing style sheets. But it occurs to me that for one: sometimes not overriding the style sheets might be preferable, and for two: it might be more performant to modify one style element than an unknown quantity of p elements. But that's just my assumption.

Performance wise, would there ever be a situation where applying inline styles to each individual element would be better than creating a style sheet? Assuming the answer might be dependent on how many elements I am styling, at one point does creating a style sheet become more efficient?

EDIT: To clarify why I'm asking the question, I'll explain a little about why I'm asking: I've recently turned a handful of JS hacks I've often copy-pasted and adapted between projects into a set of reusable CommonJS modules. They do things like setting all elements of a given selector the same height or width as the tallest or widest of the set in situations where the measure of the tallest or widest might be subject to change on a window resize or other triggers.

Here is a blog post about it: http://davejtoews.com/blog/post/javascript-layout-hacks

Here are the GitHub repos for the modules:

At this point, all these modules use inline styles, but I am thinking of switching them to stylesheets. I couldn't find a good answer about the pros and cons of either approach so I posted the question here.

解决方案

I don't have a good general answer to your question (and I'm not sure there is one), but I've run some experiments with the example you posted on Chrome 57.0.2987.98 beta, using the dev tools timeline.


Here is a breakdown of the work done in the single frame which updates 10,000 <p> elements with inline styles (left) and a dynamic stylesheet (right):


For comparison, here are the results for the same test with 100 <p> elements:


In summary, for a small number of elements, the difference is negligible. For a large number of elements, when using inline styles, the browser spends more time scripting (which is to be expected, since there is a heavy loop) and recalculating styles (I think this can be explained by the browser having to parse one style rule per-element rather than a single common style rule).

All other steps take approximately the same amount of time. In particular, the paint time does not increase when using inline styles.


For reference, I had used the following test page.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <button id="add-stylesheet">Stylesheet</button>
    <button id="add-inline-styles">Inline</button>
    <script type="text/javascript">
        let stylesheet = document.getElementById('add-stylesheet');
        let inline = document.getElementById('add-inline-styles');

        stylesheet.addEventListener('click', addStylesheet);
        inline.addEventListener('click', addInlineStyles);

        function addStylesheet() {
            let style = document.createElement("style");
            style.appendChild(document.createTextNode(""));
            document.head.appendChild(style);
            style.sheet.insertRule('p { text-align: center }', 0);
        }

        function addInlineStyles() {
            let nodes = document.getElementsByTagName('p');
            for (let node of nodes) {
                node.style.textAlign = 'center';
            }
        }

        // initialize <p> elements
        init(10000);
        function init(numElements) {
            for (let i = 0; i < numElements; ++i) {
                let p = document.createElement('p');
                p.innerText = 'testing'
                document.body.appendChild(p);
            }
        }
    </script>
</html>

这篇关于JavaScript创建的内联样式与JavaScript创建的样式表之间的性能差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆