javascripthtmlcoding-style

Create forms dynamically or statically?


I have a particular web page which requires around 6 different forms; some of them are up to 15 rows of unique labels and inputs.

I made a JavaScript library which can accept a large object and output a form. Basically, it accepts an endless object like:

var myForm = {
   row1 : {
       label : { text : 'First Field'}
       input : {
            type : 'dropdown',
            values : { 1 : 'Enabled', 0 : 'Disabled'}
       } 
   }
}

.. and so on.

Then I realised, maybe it's just better to type out every form in HTML, place it on the HTML page and hide it until required (they are implemented as overlays). However I figure this could be deemed as bad practice because:

1) The page is on a long poll, updating every 5 seconds and thus redrawing the page. Would it redraw even hidden things like the forms?

2) My HTML file will be large

My question is: Should I simply store a lot of forms for a page in HTML, or should I dynamically create them. Dynamically creating them still means I will have large objects in my javascript files. Statically embedding them on the HTML page means they may (not sure) get redrawn on every page re-draw.


Solution

  • As stated in your comment, you are already using ajax and not full page loads to update the page.

    I wouldn't worry about the page redrawing when you change the dom. Lots of stuff can be (internally in the browser) cached and there is no added request/response handling. Changing the dom is OK - doing a full page request is slow.

    Your dynamic solution might be a bit more complex than adding it as static fields on html pages and using javascript to show/hide, but i wouldn't worry about speed. If you already implemented the dynamic version (sounds like you did) how is the speed?

    If I were you, i'd ask myself this:

    1. What solution is easier to understand (for other people, or yourself years from now)
    2. What solution is easier to maintain? (What kind of changes are probable?)
    3. I kick myself for adding this: How do you complete the task fastest? (Who is paying for this and what solution did you already implement).

    It's worth mentioning that the dynamic version makes it possible to create an interface to add/remove/change fields through a backend or the like. If that is desireable you might want to sway that way. But don't design something you don't need yet, which leads to this:

    YAGNI and KISS