Difference between importing Handlebar templates and fetching them? [closed]

拥有回忆 提交于 2021-02-11 17:02:03

问题


I've seen people use fetch requests to get .hbs files that are already inside the server and could simply be imported using the import syntax. Why would that be? Is there a point to fetching files from inside the server? Wouldn't it be better to simply export const studentTemplate = "*the template*"? And wouldn't that allow for the simple export of the compiled function instead of the template itself? Are imports somehow slower (as far as I know, they shouldn't be as fetch requests deal with the network)?

E.g. instead of doing all theses activities - fetching the file from inside the server, registering all the partials necessary and then compiling the function to use - inside the file which has to output the HTML, wouldn't it be better to have a separate file which - imports the handlebars template instead of fetching it, registers the partials needed, compiles the function and only exports the function - and then just import the compiled function?


回答1:


The only reason to do this is to decrease initial page load time (by decreasing the size of a HTML/JS request). The templates can then either be:

  • loaded on-demand when a user does an action that requires rendering that template, but this may result in some latency (requiring a spinner)
  • or preloaded one by one in order of likelihood that the templates will be rendered, but this may result in unnecessary data fetching (a static import would too).

The best solution would be to precompile the templates as part of the build process, and include them in a JS bundle as dynamic imports (which the later versions of webpack support) or using AMD-style requires.This solution eliminates all overhead network and compilation latency, unnecessary data fetching and is most maintainable.

Note: it has nothing to do, as the other answer asserts, with preventing "blocking javascript execution". You could just as well embed the templates directly in the HTML in template or <script type="text/template"> tags and defer parsing/ compilation of their contents, but that would increase the load time of the initial request.



来源:https://stackoverflow.com/questions/62986109/difference-between-importing-handlebar-templates-and-fetching-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!