So normally I would only use JS to modify the dom after the user interacts with
ID: 647433 • Letter: S
Question
So normally I would only use JS to modify the dom after the user interacts with something or some event goes off. This seems right for some reason.
But I'm developing a widget based app where widgets need the capability to draw (print) themselves and it feels redundant to send the widget's html via the initial http request when I can just print them with the js method when the page loads.
Should I be trying to avoid printing html elements with JS on the page load as a rule or is it just an optimization thing?
Explanation / Answer
It depends.
Unless client-side performance is an observable concern, focus on maintainability.
That means you ideally want the translation from data to markup/DOM to be consolidated. You don't want two or three different objects, especially sitting in two or three different languages, that are each responsible for producing the same DOM structure.
If your client-side script provides progressive enhancement or needs to be crawl-able/scrape-able/Googleable, render HTML server-side. Write your server-side components in a highly modular fashion: Be able to request new markup for a single component quickly and easily. And depend as minimally as possible on direct client-side manipulation of the DOM.
Alternatively, if your app is "highly interactive" or dependent on client-side script, the server probably doesn't need to know anything about the final markup/DOM as it pertains to these interactive components. Send "bare" markup, XML, or JSON for your JavaScript library to consume and display.
Don't spend time optimizing for client-side rendering performance unless it's a known issue.
If you have doubts, and even if you don't, model your app after another successful app that's similar. Open your browser's network profiler and see what comes over the wire and when.
Personally, I've been tending towards client-side DOM construction and have found even the more ancient devices, running modern browsers, perform perfectly well using this strategy. The burden on keeping my client-side code and server-side code is greatly reduced.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.