iCanHaz.js - separating templates? - javascript

Using ICanHaz.js is really nice - it's dead simple to create, load and render templates from javascript objects. However, in a somewhat big javascript application, the .html-file that initiates my application and contains all the ICanHaz-templates has become really crowded with template-script tags.
So how should I separate my templates to make things clear again? Are there an alternative to IcanHaz.js that applies better to larger projects?

Most client side template engines have the same concept.
You could load the templates remotely using XHR but that will add a terrible overhead of the HTTP request.
A better alternative could be creating each one in its own file, and having a server side script merge then in to your HTML page.
Finally, the last option is to add them inline in your javascript rendering functions - this will work for very small templates.

Related

Best way to structure reusable code using Node.JS, EJS, and front end JS?

Evidently the 'Software Engineering' exchange was the wrong place to ask this:
I'm more or less learning the MEAN stack (have yet to start on Angular, so currently using straight vanilla JS for front-end) and part of what I'm building for my portfolio is a drag-and-drop form builder.
Currently the form has sections, which contain questions, which can contain multiple options as well as multiple follow up/sub questions (which can then contain their own options, but not follow ups).
EJS helps me with the original render of the stored form using nested for..of loops, however my question comes into play when adding new elements to the form.
Currently, I have vanilla front-end JS that is looking at some template tags within the page, then filling those in for new sections, questions, and options.
However it doesn't seem very DRY because I'm using essentially the same logic in EJS when initially rendering the page (albeit multiple times).
To make my code more reusable, should I write functions on the back end which are cast into the EJS render call both for the initial render and then available to the front-end JS, or cast the EJS variable containing the form (from MongoDB) into the front-end JS directly and use functions in there to both draw the page initially, as well as add new elements? Both of these, hopefully, would make use of template tags in the HTML. Is one faster and/or safer than the other?
Another option could also be to use EJS partials for sections, questions, and options to render the page, but I wouldn't know how to incorporate that into the front-end JS to add new elements without using templates, which is essentially what I'm doing now.
I'm going through the same ordeal right now.
From my understanding, your scenario requires using both the server side rendering (using EJS) and front end rendering using HTML templates and you want to know what's the best approach to go about it.
The short answer: cast everything on the front end and do the heavy lifting there.
I've used EJS components (includes) and they are simply not designed to be interactive. Data flow is basically one way and there is no state management that I know of.
You don't have to do this for the entire project mind you, this can be done for certain pages only where interactivity is very heavy.
Just import Vue or any other SPA framework on the said page and act as if it is a single page App. That way you don't miss out on server side benefits when you need them on other pages of the project.
Of course going into complete code split (API/SPA) would be the more traditional way but I'm sure there is a reason why you're forced to use server side rendering.
It helps that both (server/front end) use JavaScript which might not lead directly to code sharing but will surely make it easier to write the needed functions in similar ways on the back end and front end.

Are there any benefits of pre-fetching templates in angularjs?

I have question concerning optimising application. I have application with multiple directives, so I decided to build single min. css and js file for them all. But at the same time, I was thinking of another way.
What if I would also build one big, minimalised HTML file? Angular allows including templates from script tag:
<script type="text/ng-template" id="tempName">
Template content
</script>
If so, what would be downsides of injecting every directive's HTML in one big file? Would it be any better than multiple small files and firing request when they are needed?
I know, that it wouldn't be so good if we have big application with multiple views, but user only stays at few of them. My idea is to build this file for smaller directives, that shoulnd't cause any problems, right?
What do you think of this?
Like anything there are pros and cons to this approach of caching templates.
Pros:
No need to fetch the template - good for offline capability
If network is slow and this fetch is going to cause some lag as the directive, route, include must resolve the templateUrl. In such cases pre-fetching helps in improving the smoothness of feel.
Pre-fetching also pre-compiles the template ready to be used as it puts in the templateCache.
Cons:
In a large application if all the templates are prefetched we are essentially utilizing more memory to store all the templates when only a handful might get used.
If the prefetched templates are fetched during loading it causes additional request.
If the pros exceed in your application you may want to use some build tool such
as:
gulp-angular-templatecache
webpack-templatecache
grunt-angular-templatecache
... and more
Each file you include is an additional request the browser has to make back and forth, so if u can include it in the same page, then its going to be faster and more efficient.. the main reason for excluding in multiple files is simply for organisation vs the 0.01ms different in page load time.
You can also use something like grunt to work with separate files and then have grunt automatically concat and minify your files for you for on the fly optimization.

Grabbing HTML from another page

I have two HTML files: One acts as a template, supplying the navigation, sidebars, etc., and the other has the main content. I'm trying to figure out how best to insert the content into the template. I need persistent URLs, so my plan was to have the content page essentially replace itself with the template, plugging the text back into the resulting page. I'm really new to front-end programming and I'm suspicious that this may be an anti-pattern, so my first question is about whether I'm barking up the right tree. The problem seems universal, and I'm sure there must be a best practice, though I haven't yet seen it discussed. If this is an acceptable way to proceed, then what JavaScript function would allow me to access the HTML of two different pages at the same time?
[EDIT: It's a small page on GitHub]
Do not do this. At current implementation HTML is not designed to be template engine. You can use HTML import but it has not full support in browsers. (compatibility table).
Usually this problem can be solved with:
Use frontend framework. Libraries like angular.js or polymer.js (and so on) usually has support of importing HTML documents in different forms.
Build your application HTML. Task runners like grunt.js usually has plugin that includes HTML.
Use server side technologies to extend your HTML from base layouts
If your application have to be consisted from different HTMLs I recommend you to try polymer. It is polyfill for web components and designed to work in such way by default.
UPD:
About edit to your question. It seems like you just need template engine for HTML. You can google for it. I use nunjucks - javascript port of python's template engine jinja2. It is lightweight, simple and can be compiled right in browser.
Another way is to use special tools for building static web pages. You have mentioned that your page is blog build from simple HTML pages. Try to use pelican. It is the static websites (blogs) generator. It is simple and fast. You can build your HTML even on your local machine and just push your HTML pages to github.

Javascript code management in asp controls

We're looking for a way to manage ever-increasing javascript code for our asp controls (used with RegisterClientScript family). The classic way was to have javascript encoded into string constants inside c# code but now it's getting bigger and you don't want to develop inside c# string. Having code in external file and convert/copy it into a string form before compilation is also somewhat ridiculous. Plus in these scenarios almost same code is sent several times with each instance of the control.
Other important criteria is to have the scripts self-sufficient, with only external dependency on jquery&co, so having control-specific javascript files somewhere else is not desired. All the relevant parts have to be in one place.
My personal best option so far is to have Javascript split into two parts:
- "code behind"-like js file compiled as embedded resource into assembly. This is about 3 times slower than string concatenation but. Plus it brings options for caching and direct-from-file without recompiling for debugging. This part is delivered inline once per page containing the control.
- tiny initialising proxy function calling the main script with control-instance specific parameters. These are delivered also inline but once per control instance.
I'm sure we're not the only ones scratching our heads about this.
So how do you do that?
Update.
Getting rid of .net specifics, situation is following.
We have some 100+ reusable server-side components each possibly containing some javascript client-side functionality. These controls are of course not used in every page so packing the javascript into one common lib is not desired. On the other hand, having 20+ references to external javascript files each being 1-2Kb in size is also both headache for maintenance and traffic overkill.
That is why we want to have the component know and care about its own javascript inclusion.
On the other hand, if you have a project where these components are spread into several libraries, you don't really want for them to depend on some particular filesystem layout which may be of course standardised but it's too much of responsibility for a vehicle tire to enforce your cola choice in a diner, imo.
If you have JavaScript code that is re-used by several controls - why don't you want this in an external *.js file? This will allow you to maintain formatting, and yet still serve up a minimized, gzipped and client side cachable file.

Internationalization in javascript

I have a legacy JSF application. Now that we want to add i18n support to the application. Some portion of the textual content comes from javascript code and is added dynamically. How do we best internationalize this? The approach that i have in mind is to get the entire resource bundle as a json object from a server side script and then use jsonobj.propname wherever needed.
Is this is a right approach? Do you have any better solution?
That certainly sounds like an approach that will work.
A commercial application I worked on generated a separate JavaScript library for each language as part of the build process. This was done for performance reasons - the results were minified, a single file reduced latency and the results were cached "forever." But not every application has such tight constraints.

Categories