JavaScript application often use one of the following methods:
- They use empty HTML elements (which exist in markup but are invisible开发者_如何学运维 because of
display:none
) - They generate markup dynamically
- A combination of both
What is the best case for each of these methods? When should I prefer one over the other, and why?
It all depends on what you're trying to do.
If you want to add elements to a page, and you know how many you need, you can have them on the page and hide/show them when needed.
If you want to add a dynamic number of new elements, you can just make them on-the-fly, because having them on the page to begin with may not work if you need more than you added.
You can also clone existing elements, and change their attributes, to add elements to a page.
This all depends on what you're trying to do.
For example:
- You have a form that can accept a dynamic number of inputs. You don't know how many the user wants, so having them on the page to start with (hidden) won't help. You can either clone the existing inputs (and change their values), or create new ones and add them.
- You have a form that allows from 2-5 names to be added. Since there is a fixed amount, you can add 5 inputs, hide 3 of them to begin with, and show them if needed.
So, there are different methods for what you are trying to do.
Things to considerate:
- Less HTML code, less time to load web app.
- The main goal is minimize the HTML Reflow: http://code.google.com/speed/articles/reflow.html
I choose A combination of both to optimize the load time.
精彩评论