JavaScript:动态(即时)创建样式元素的优点和缺点 [英] JavaScript: Advantages and disadvantages of dynamically (on fly) creating style element

查看:117
本文介绍了JavaScript:动态(即时)创建样式元素的优点和缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我们可以动态创建< style> 元素,并附加到< head> 对大量元素应用CSS规则。


  1. 这种方法的优点或缺点是什么?


  2. 如果它真的提供了与JavaScript迭代相比的元素的性能增益。


  3. 哪一个更快或更慢? JavaScript迭代元素或在浏览器中动态添加CSS?


  4. 处理时间如何?处理负载?


为了更好地理解我使用此方法的问题,请参阅以下示例:



示例:如果我拥有20列或更多列,1000行或更多列的表格,如下所示:

 < table border =1class ='no-filter'> 
< thead>
< tr>
< th data-title ='id'> Id< / th>
< th data-title ='name'> Name< / th>
< th data-title ='family_name'>姓氏< / th>
< th data-title ='ssn'> SSN< / th>
//其他表数据
< / tr>
< / thead>
< tbody>
< tr data-id ='1'data-name ='nick'data-famil_name ='jackson'data-ssn ='123456'>
< td class =column column1> 1< / td>
< td class =column column2> Nick< / td>
< td class =column column3> Jackson< / td>
< td class =column column4> 123456< / td>
//其他表数据
< / tr>
//其他行
< tr data-id ='809'data-name ='helga'data-famil_name ='jhonson'data-ssn ='125648'
< td class =column column1> 809< / td>
< td class =column column2> Helga< / td>
< td class =column column3> Jhonson< / td>
< td class =column column4> 125648< / td>
//其他表数据
< / tr>
//其他行
< tr data-id ='1001'data-name ='nick'data-famil_name ='jhonson'data-ssn ='216458'
< td class =column column1> 1001< / td>
< td class =column column2> Nick< / td>
< td class =column column3> Jhonson< / td>
< td class =column column4> 216458< / td>
//其他表数据
< / tr>
//其他行
< / tbody>
< / table>

如果有人需要jsFiddle示例,我可以稍后创建。



情况1:如果我要动态隐藏仅包含SSN数据的表列。我可以应用几种方法来做到这一点。这种方法可以分为两大类。在第一类解决方案中,我可以迭代 td 元素,并动态更改列的样式。在第二种方法中,我可以通过动态创建一个或应用预定义的CSS规则来应用CSS 问题。在这个问题OP询问对长表中的某些表列应用CSS规则。我建议创建样式元素与规则在飞行,它的工作正常。我认为这是因为浏览器应用的样式内部机制,并且提供比迭代元素和应用样式到每个项目更好的性能。

解决方案

动态生成CSS不好。不要这样做。



通过生成动态CSS工作的解决方案可以转换为不需要动态CSS的解决方案。



如果您需要一个示例,请参见我的答案: jQuery to更新实际CSS






直接回应您所链接的案例:



这看起来像一个非常奇怪的用例。具有1000行的表的页面已经是一个坏的起始位置。你不能合理地在屏幕上1000行,并期望任何有用的交互。 CSS不是这里的问题。如果表格较小,性能问题就会消失。



有可能的其他方法,比OP上建议。您不需要(动态)为每个单元格添加类,您可以将类放在生成时间,例如:

 < table class =no-filter> 
...
< td class =filter1 filter2>< / td>
...
< / table>

然后有类似:

  table.filter1 td.filter2 {display:none; } 
table.filter2 td.filter1 {display:none; }

您只需更改表格上的类别以说明应用哪个过滤器。



CSS不仅仅是一个锤子,它是一个完整的工具集非常精致和非常强大的工具。

$ c
$ b


静态CSS的优点应该是显而易见的:


  • CSS实际上是在CSS中(不是在JavaScript中) )。

  • 您可以做模板,也可以添加一些视觉回归测试。



  • 也有一些性能问题。我可以看到浏览器厂商优化AGAINST动态CSS。我的意思是,如果有静态CSS的优化,降低动态CSS的性能,你只是可能做出这种权衡。


    In JavaScript we can create <style> element dynamically and append to <head> section in order to apply CSS rule for huge number of elements.

    1. What is advantages or disadvantages of this approach?

    2. If it is really gives performance gain comparing to javascript iteration over elements. What goes behind the scene (inside of browser)?

    3. Which one is faster or slower? Javascript iteration over elements or adding css dynamically in browser?

    4. What about processing time? processing load?

    For better understanding the issue where I used this approach see following example:

    Example: If I have table with 20 or more columns and 1000 rows or more as following html:

    <table border="1" class='no-filter'>
        <thead>
            <tr>
                <th data-title='id'>Id</th>
                <th data-title='name'>Name</th>
                <th data-title='family_name'>Family Name</th>
                <th data-title='ssn'>SSN</th>
                //Other table data
            </tr>
        </thead>
        <tbody>
            <tr data-id='1' data-name='nick' data-famil_name='jackson' data-ssn='123456'>
                <td class="column column1">1</td>
                <td class="column column2">Nick</td>
                <td class="column column3">Jackson</td>
                <td class="column column4">123456</td>
                //Other table data
            </tr>
            //Other rows
            <tr data-id='809' data-name='helga' data-famil_name='jhonson' data-ssn='125648'>
                <td class="column column1">809</td>
                <td class="column column2">Helga</td>
                <td class="column column3">Jhonson</td>
                <td class="column column4">125648</td>
                //Other table data
            </tr>
            //Other rows
            <tr data-id='1001' data-name='nick' data-famil_name='jhonson' data-ssn='216458'>
                <td class="column column1">1001</td>
                <td class="column column2">Nick</td>
                <td class="column column3">Jhonson</td>
                <td class="column column4">216458</td>
                //Other table data
            </tr>
            //Other rows
        </tbody>
    </table>
    

    If somebody needs jsFiddle example I can create one later.

    Case 1: If i want to dynamically hide only table column which contain SSN data. I can apply several approach to do this. This approach can be divided into two major category. In first category solutions I can iterate over td elements and dynamically change the style for the column. In second approach I can apply CSS by dynamically creating oneor use predefined CSS rules as given here by @Frits van Campen. (Note: @Frits van Campen is good solution for given case. But I want to discuss further more then manipulating table row showing and hiding.)

    I can create dynamic CSS rule as following:

    td:nth-child(3)
    {
      display:none;
    }
    

    Or apply predefined CSS rule:

    table.no-filter td.column3
    {
       display:block;
    }
    table.filter3 td.column3 
    { 
       display: none; 
    }
    

    Here are jsFiddly examples:

    1. Iteration
    2. CSS on fly

    Here is time comparison using console.time method which I found here.

    Left is dynamic css and right is iteration approach.

    Perhaps, it is not appropriate one because it calculates appending style element vs iterating over elements. All iteration over element in dynamic CSS will be done by browsers internals. However if we think our script response time dynamic css is faster. Note: iteration approach will be faster in pure JavaScript comparing to jQuery. But how much faster i do not have results. So you can more in your answers.

    Case 2: Now, I want to highlight table row <tr> which contains user with name 'Nick'. Here you can note that table row has data attributes like name, family_name, id and etc. So, here again I can iterate over elements using javascript or any other library tools or can apply some dynamic rule (I do not know whether it is possible or not apply predefined filters as in case 1.)

    CSS rule:

    tr[data-name ~='nick']
    {
        background-color:red;
    }
    

    In this case I can do a lot of fun filtering by applying CSS rule dynamically.

    Update: Example given here is for simple overview of the problem. And some optimized iterations can perform equally fast in javascript. However I consider only table which does not have dipper child elements comparatively nested ul elements where traversing in order to select element can be difficult.

    Important: I only give tabel example here to make clarification with what kind of issue I faced if it is irrelevant feel free to edit the question and delete this part. Also please state your answers clearly in scope of question. Here I am not asking about 'Did I implemented in good way or not?' I am asking what is of advantages or disadvantages of dynamically creating style elements has in terms of browser internal mechanisms.

    P.S. and example: Why I came with this idea? I answer recently for 'How to hide columns in very long html table' question. In this question OP asks about applying CSS rule for certain table columns in long table. I suggest to create style element with rules on fly and it works fine. I think this is because style applied by browsers internal mechanisms and gives better performance than iterating through elements and applying style to each item.

    解决方案

    Dynamically generating CSS is bad. Don't do it.

    A solution that works by generating dynamic CSS can converted to a solution that doesn't require dynamic CSS.

    If you need an example, see my answer here: jQuery to update actual CSS


    To respond directly about the case you linked:

    This seems like a very strange use-case to me. A page that has a table with 1000 rows is already a bad starting position. You can't reasonably fit 1000 rows on your screen and expect any kind of useful interaction. CSS is not the problem here. If the table were smaller the performance concerns disappear.

    There are possibly other approaches than the on OP suggests. You don't need to (dynamically) add a class to each cell, you can put the class there on generation time, like:

    <table class="no-filter">
    ...
      <td class="filter1 filter2"></td>
    ...
    </table>
    

    Then have something like:

    table.filter1 td.filter2 { display: none; }
    table.filter2 td.filter1 { display: none; }
    

    You only change the class on the table to say which filter applies.

    CSS is more than just a hammer, it's a whole tool-set of very refined and very powerful tools. Make sure you use the right ones.


    The advantages of having static CSS should be self-apparent:

    • Much easier to understand, test, debug and maintain.
    • The CSS is actually in CSS (not in JavaScript).
    • You can do templating, maybe add some visual regression tests.

    There are also some performance concerns. I can see browser vendors optimizing AGAINST dynamic CSS. By this I mean if there is an optimization for static CSS that reduces performance of dynamic CSS you just might make this tradeoff.

    这篇关于JavaScript:动态(即时)创建样式元素的优点和缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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