What is the most efficient way to create HTML elements using jQuery?

后端 未结 12 2662
甜味超标
甜味超标 2020-11-22 06:40

Recently I\'ve been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelming

12条回答
  •  眼角桃花
    2020-11-22 06:56

    You'll have to understand that the significance of element creation performance is irrelevant in the context of using jQuery in the first place.

    Keep in mind, there's no real purpose of creating an element unless you're actually going to use it.

    You may be tempted to performance test something like $(document.createElement('div')) vs. $('

    ') and get great performance gains from using $(document.createElement('div')) but that's just an element that isn't in the DOM yet.

    However, in the end of the day, you'll want to use the element anyway so the real test should include f.ex. .appendTo();

    Let's see, if you test the following against each other:

    var e = $(document.createElement('div')).appendTo('#target');
    var e = $('
    ').appendTo('#target'); var e = $('
    ').appendTo('#target'); var e = $('
    ').appendTo('#target');

    You will notice the results will vary. Sometimes one way is better performing than the other. And this is only because the amount of background tasks on your computer change over time.

    Test yourself here

    So, in the end of the day, you do want to pick the smallest and most readable way of creating an element. That way, at least, your script files will be smallest possible. Probably a more significant factor on the performance point than the way of creating an element before you use it in the DOM.

提交回复
热议问题