Dynamic/static loading components/pages/HTML - javascript

I would like to ask your advice on our situation about dynamic/static loading components.
We're developing a "multi language teaching app" for Android/iOS. For UI text we use ng2-translate plugin (JSON files for each language). For the lesson content we use separate HTML files for each language. In the beginning the user selects a language to learn and then sees related lessons as a list (which comes from a JSON file too). Clicking a lesson loads the related HTML file and dynamically compiles directives/pipes in it (which makes it more interactive). By directives, I mean simple functions like showing a toast when user clicks a custom directive, like this: <example tooltip="explanation to show as a toast">An example sentence</example>. But maybe we can use more complex directives in the future.
Up to building the app, everything goes well in browser. But the AoT compiler does not support "dynamic loader components" in mobile devices, so we need to decide whether or not use this approach. And at that point I'm really confused. We may change our structure but I don't know which way is better.
As far as I can see, we have three options (if there are more, please enlighten me):
Stop using html files and convert each of them into a component with html templates (using AoT compiler (--prod mode)):
Be able to use directives/pipes
Gain interactivity
Gain performance (that's the main purpose of AoT, right? but what if I use hundreds of html pages/components? isn't it a bulky solution?)
Use hundreds of pre-compiled html pages for grammar lessons, stories, texts...
Load pure HTML files into an innerHTML of a loader component (using AoT compiler (--prod mode)):
Don't use directives/pipes
Loose interactivity (except being able to use simple HTML tags like p, strong, em, table etc. --if we count this as an interactive content)
Gain performance a bit (as we use AoT?)
Load HTML files dynamically as components via one dynamic template component (using JiT compiler (--dev mode)):
Be able to use directives/pipes
Use separate html files
Gain interactivity
Loose performance
Do something that Angular generally does not recommend
I can't decide what to do now, if I want more interactivity, I should drop the performance that Angular proposes.
I just wanted to be able to handle these grammar lessons in a simple syntax (like HTML) as seperate files and not to use/declare components for each of them...
What would you recommend?

I asked same question to Ionic forum and I decided to implement the solution of a user that replied to me:
I went through this with Markdown, tried a bunch of things, and here's what I eventually settled on:
Store your objects however is convenient for you. In my case, that's markdown source.
Define two components; we'll call them skeleton and bone for now.
skeleton has an input property giving it the source. In ngOnChanges, you need to parse that source into an array of elements, each corresponding to a different type of bone.
skeleton's template looks something like this:
<template ngFor let-bone [ngForOf]="bones">
<app-bone [bone]="bone"></app-bone>
</template>
Make sure each bone has a discriminator indicating its type, and then the BoneComponent template is a big giant switch:
<blockquote *ngIf="bone.tag === 'blockquote'">
<app-bone *ngFor="let child of bone.children" [bone]="child"></app-bone>
</blockquote>
<br *ngIf="bone.tag === 'br'">
... every other block-level element we support...
Note that this can work recursively if you need it to, in that the
inside of the blockquote case is effectively another skeleton. I'm
using HTML elements here, but the general technique works equally well
for other user-defined components (as types of bones).

Related

Should I recreate all my page from scratch (html and css) if I begin using React/flux?

I have alreayd built a few pages of my app. As i need a javascript framework and sub second dynamic pages I think I'll try React/Flux.
The thing is despite much reading, I don't fully understand if you can keep my EXISTING codebase (html/js) and only use React (jsx , modules) on certain blocks of the web page that need interaction with database/dynamic actualization?
Let's take an example:
my page has a lot of stuff : bootstrap I adjusted a lot(with css) that is actually using behind the scene javascript/the DOM ex for dropdowns, and other stuff), respond.js for enabling media queries on ie8 (using I guess the DOM), and many third party tools like intercom.io or even google analytics js tracking window on the bottom of my screen.
you can see here what the pages look like.
My need: I just need dynamic adjustments and real time features on the block (D), all the other, the header (B), intercom(C) and the rest could stay like they are, it would save me some much time if i can keep them in their current html code.
So here are my question:
(1) do I have to convert EVERYTHING on the page on react or only put in jsx/react the block (D) and keep the rest as it is ?
Related to (1) I want to leverage the main advantage brought by React (the virtual DOM and the diffs), would I still be able to use it EVEN if the whole page is not on React ?
If the answer is basically "it's all or nothing, you've got to do it ALL in react jsx and redo your whole page", convert your html and find alternatives to all your js scripts that use the DOM such as dropdowns, light boxes, intercom.io script, google analytics scripts then is it hard? i mean or can i keep the css and just use this to change the html http://facebook.github.io/react/html-jsx.html ? that would be really easy but i fear there is a catch here...:)
In terms of the view layer of your app everything can be done with React
(Yes react can do everything you require)
The first thing I would suggest is to head to the react site for the docs, do a few tutorial use Google & YouTube and then start to re-build your app from fresh with react but not entirely. (Use JSX).
Because you now understand how React works and how to use props and states you will likely end up merging fragments of your app at a time.
The most important thing to consider is context. React is simply Javascript so you can bind, call and apply any objects from your existing app.
var blockA = React.createClass~
blockB = React.createClass~
blockC = React.createClass~
blockD = React.createClass~
React is just components, each block is a component.
But I can't stress more, understand the basic principles of react, it's not hard at all.
Edit...
YES use JSX I thought it was stupid initially but it's excellent!
With DOM manipulation it's all or nothing. React uses its copy of the DOM to manipulate the actual DOM faster. For parts of you code that doesn't touch the DOM it will not make a huge difference in React but React has a beautiful workflow by passing state changes down to its component's children. Really it's up to you but If you are using React do all DOM stuff in react. 70+% of what you are trying to do is likely DOM manipulation.
My advice in general, don't think too much about how "hard" it will be. Think about how quick you can learn the basics. It's quite easy to grasp.
I am new to React, but from what I've gathered you may sprinkle in React code as desired. You do not have to re-write your entire application. This includes the ability to use the features you outlined wherever you need them.

Whats the best way to structure my js application, when my views / controllers need to be in the same file

I am Building a learning application where there are a bunch of different page types that a learner will go through and do activities. It will be a SCORM compliant learning object.
This is the structure I have so far...
application/
models/
scorm.js
sequence.js
session.js
pagetypes/
multichoice.js
truefalse.js
basic.js
utilities/
jquery.js
api.js
My pagetypes do the viewing and the controlling, should I seperate these out? The reason I have combined them is so when I build a new page type, I can just drop it into that folder and it will get recognised straight away by the code.
What do you guys think? amidoinrite?
I'm guessing you're separating out methods based on type of page interactions.
I don't see any reason not to do it your way. So long as everything the sco needs is in the manifest you can subdivide your scripts however you want. It might save just a bit of load time to separate out separate page types... But only if you are only loading what you need into the HTML page, & you are actually navigating pages within a sco session. If you're loading all script into a single HTML page, & then dynamically changing the content of page divs, then your scripts are all loaded 1 time & you may as well have 1 minified file for all page type scripts.
I would probably go with the latter, & tie interactions to classes or ids in the markup. 1 file, less work to minify, & I can use in other packages without having to make sure that I have every page type I need...
With JavaScript it can be tricky to separate it out since it lives so closely to the view. As long as the data is separated from the actual view (which it looks like it is in your example) it will be a good design. I would argue that the pagetypes are more controllers and the HTML is the view. The most important part is to keep the model separated from the view. Unless you're trying to build reusable JavaScript/HTML components it's ok for pagetypes to blur the role of controller and view.

Best way to package multiple jQuery templates in single xHttpRequest?

Update: after another day of digging
into this issue, I have found that the
current jQuery template lib provides
no way to do this. this article
describes a good approach.
I would still like to hear of any
additional thoughts on doing this. The
article linked above requires that the
returned string of templates be
inserted into the DOM. Seems as though
leaving the DOM out of this would be
ideal, and less overhead on the
browser. Imagine a large page, with
multiple composite templates that may
not get used. Although, maybe because
the templates are wrapped in a script
tag, there is only a single DOM item per template? Come on, let's
hear some thoughts...
Using jQuery template libs, what's the best way to combine multiple, related, relatively small templates together? Do you need a single <script> tag for each individual template? What about in the case of dynamically pulling these templates via AJAX? Can I combine these templates somehow?
Consider the following:
<script id="movieTemplate" type="text/x-jquery-tmpl">
{{tmpl "#titleTemplate"}}
<tr class="detail"><td>Director: ${Director}</td></tr>
</script>
<script id="titleTemplate" type="text/x-jquery-tmpl">
<tr class="title"><td>${Name}</td></tr>
</script>
Now because these two templates are very closely related (and one depends on the other) it would make sense to consolidate these into a single AJAX call, and get them both at once. I have a few ideas, but I'd like to know if there is common/best way to do this? Currently I pull in a chunk of HTML, and then do a .find() to get the specific peice of HTML for a template... e.g.:
var templatePackage = fancyAjaxCalltoGetTemplates();
"templatePackage" might then look like this:
<div id="templatePkg">
<div id="movieTemplate">
{{tmpl "#titleTemplate"}}
<tr class="detail"><td>Director: ${Director}</td></tr>
</div>
<div id="titleTemplate">
<tr class="title"><td>${Name}</td></tr>
</div>
</div>
I could then do:
var titleTemplate = jQuery.template('titleTemplate', $(templatePackage).find('#titleTemplate') );
and
var movieTemplate = jQuery.template('movieTemplate', $(templatePackage).find('#movieTemplate') );
...let me know what you think... what would you do?
I like the referenced article in your update, except the assumption that you can't cache templates unless you insert them into the DOM. From the jQuery.tmpl documentation,
"To cache the template when using markup that is obtained from a string (rather than from inline markup in the page), use $.template( name, markup ) to create a named template for reuse. See jQuery.template()."
Using this, we can build a javascript template management system that allows us to load as many templates at a time as we need while keeping the DOM clean. On the client, keep a hash of template objects by name. You can use your favorite object based javascript pattern here, but I would think the structure could be like this:
templates[templateName] = {
templateMarkup: markupFromServer,
loadedAt: Date.now(),
compiledTemplateFunction: jQuery.template( templateName, markupFromServer )
}
Then use the templates to generate HTML like this:
templates['unique-name'].compiledTemplateFunction(inputData)
Then, build an unload mechanism to free up memory:
function unload(templateName) {
delete templates[templateName];
delete jquery.template[templateName];
}
Most importantly, you now have a method of storing multiple templates so you can make requests like: $.get('/TemplateManagement/Render', arrayOfTemplateNamesToLoad, loadManyTemplatesSuccess) to load multiple templates at a time. The only thing we need is a controller TemplateManagement that will take an array of template names as an input and return JSON that pairs a template name with its markup. There are a few ways to do this but it seems to me the most convenient is to define partial views for each template. In ASP.NET MVC 3, you can use this technique and RenderPartial to emit each template's markup into a JSON response. You can either name the partial views the same as the templates or map the names in some custom way.
OK, I read the article you reference in this post. As I see it, his way is probably one of the best ways to load up the template page(s). The only thing I don't like is the asynchronous problems that could crop up, esp. if you need to immediately do some templating before the async get returns... plus any binding issues that could happen before it returns something. In several projects I have done I use his "ancient" SSI (server side includes), but I just use something even easier like:
<% Response.WriteFile("this_page_template_file.html"); %>
You could put it anywhere where you'd place a tag. Like he says, just put in only the templates you need, or maybe include two templates: one is a "base" template with commonly-used items and the second one would have the page-specific ones with template references {{tmpl}}.
Is this even close to an answer? ;-)
[First off, great question. I love this topic]
I have no experience with the plugin "jquery-template-libs", but there is a particular lightweight javascript template plugins that are becoming almost a standard and plays very nicely with jQuery, which is probably better suited for the task than JTL, Mustache:
https://github.com/janl/mustache.js
It's got something that's called a "partial" which is essentially a way to include smaller templates within another one. Which sounds like it will help you out a lot.
On top of that there is a library called ICanHaz.js:
http://icanhazjs.com/
ICanHaz essentially extends Mustache to include built in functionality for templates and works incredibly well.
Mustache/ICanHaz allow you to add templates by variable, by a json call or by using tags. The choice is yours.
I know this is an old question but you might want to take a look at Closure-Templates. They provide the kind of functionality you're after with the added advantage of being compiled into JavaScript at compile-time instead of at run-time in each user's browser.
If you do decide to look into using them then I'd suggest using plovr for building them.

Is there a XSLT-like JavaScript templating system?

I have a big chunk of deeply-nested semi-structured JSON and would like to generate HTML from it. At the moment I'm using jQote2, but much of the code inside my templates deals with dynamically finding the next template to render and then calling it. What's a single <xsl:apply-templates> in XSLT takes several lines with JavaScript and jQuote. I dearly miss the pattern matching capabilities of XSLT. Is there any (templating) library in JavaScript that allows me to dynamically decide from the data which template to render?
Here is an example of what I want. Suppose I have a JSON structure like this:
{
items:[
{foo:1, bar:2},
{foo:7, baz:99},
{foo:8, quux:3}
],
curdate:'2010-07-07'
}
I'd like to have a "root" template that renders the curdate field and then renders the items. If an item contains a "bar" field, I want the item to be rendered with a template named "tpl-bar" (or something like that), otherwise a template named "tpl-foo" should be used. Filtering capabilities (like "do not render items that have a quux field") would be a nice-to-have.
I am aware of the JSONT library, however from what I see it's not dynamic enough to accomplish what I described.
If no such library exists, I'm on the verge of giving it a shot myself. But I'm not sure how to do it at the moment. Code examples or general descriptions would help me.
There's also JSLT, from what I remember reading it's a little more advanced than JSONT. I've never actually used it, though. The problem is that these libraries aren't hugely popular and so not a lot of work gets done to improve them and build upon them.
On the plus side, it's open source so if you don't find a feature you want you could attempt to add it yourself.

UI Patterns in JavaScript

What UI patterns do you usually use in JavaScript?
By UI patterns I mean best practices to be used to build and organize UI, generated/managed from JavaScript (apart from libraries like jQuery or YUI).
For example, if you came from .NET world you are familiar with MVC (Model-View-Controller) patterns family. In the world of WinForms and ASP.NET you will meet Model-View-Presenter. In WPF most likely you will find MVVM (Model-View-ViewModel) approach.
And what about JavaScript?
Patterns are usually language-agnostic. If a pattern has value, barring certain edge cases it will have value regardless of what language or technology you're using. Take MVC. The concept of separating the model from the view from the controller has value regardless of whether the model is implemented with an RDBMS or some other technology, whether the view is HTML or Swing or X.
Where you see certain patterns applied more in one technology than another, it usually just means that the developers of the technology had a particular approach that they supported more fully than others.
JavaScript itself doesn't impose any particular pattern on you. Some JavaScript frameworks, like YUI or Dojo or Glow will tend to lead you one direction more than another.
At the end of the day, look at the problem you're solving, the resources and experience you have, and follow the patterns that make sense.
I'd like to recommend Ross Harmes & Dustin Diaz's book, Pro JavaScript Design Patterns, definitely the best resource on this subject, and definitely worth a read.
There’s also a very interesting article on JavaScript MVC in the latest issue of A List Apart.
A good approach to building GUI application is that of browser:
using markup for UI layout
using javascript UI logic
using CSS for UI styling
Most of modern GUI frameworks (ExtJS, Dojo etc) offer APIs that greatly help building GUI in JavaScript solely. But there is another GUI framework Ample SDK that brings the before mentioned separation of concerns. It allows for using XML-based languages (XHTML, XUL, SVG) for layout, CSS for style and DOM APIs for UI logic.
To orchestrate a client-side GUI application you can use either MVC or a little bit more advanced pattern PAC, as for the former - there is a PureMVC implementation available
Take a look at the following snippet (only concerns UI logic, not app logic, to be built with MVC/PAC):
index.html
<script type="application/ample+xml">
<xul:tabbox onselect="fOnSelect(event)"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<xul:tabs>
<xul:tab label="checkbox" />
<xul:tab label="textbox" />
<xul:tab label="datepicker" />
</xul:tabs>
<xul:tabpanels>
<xul:tabpanel>
<xul:checkbox />
</xul:tabpanel>
<xul:tabpanel>
<xul:textbox />
</xul:tabpanel>
<xul:tabpanel>
<xul:datepicker />
</xul:tabpanel>
</xul:tabpanels>
</xul:tabbox>
</script>
index.css
#namespace xul url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
xul|tab:focus {
color: red;
}
index.js
function fOnSelect(oEvent) {
alert(oEvent.currentTarget.selectedItems.length)
}
As i know there are no specific patterns for Javascript yet. But I think there is a potential for something like widgets(component) approach. Since mainly we use javascript to empower our html code. It is logically that we should connect our every javascript object to html tag. So here we have something like Model(jsObject)+View(HTMLrepresentation). To get MVC we need controllers and we have Events for this. In this case we will have incapsulated easily extensibel component.
for example:
// this is a part of some FormValid.js
<script>
function FormValid(){
}
FormValid.prototype.validate=function(){...}
</script>
//this is our HTML
<form id="form1"...onsubmit="this.jsObject.validate();">
</form>
<script>
//all the following stuff could be solved in one line, but you need to create some helper. Like Components.Attach("FormValid").to("form1");
var newObj=new FormValid()
var form=document.getElementById("form1");
from.jsObject=newObj;
newObj.htmlObj=form;
</script>
Also I have an idea of using template engines like Zparser to separate view and model. I am developing js library for this, so I am in this question right now.
We have core object with view method. All our classes have it like a prototype at he end. This method gets templates property of class and using some templates parser generates HTML basing on our model. This HTML is inserted in htmlObj node so the VIEW of our object is updated. This is basically an idea and our code becomes:
// this is a part of some FormValid.js
<script>
function FormValid(){
}
Components.extendCore(FormValid);
FormValid.prototype.validate=function(){...}
</script>
FormValid.prototype.templates={
main:'<form class="form1"...onsubmit="this.jsObject.validate();">...</form>'
}
//this is our HTML
<div id="form1"></div>
<script>
Components.Attach("FormValid").to("form1");
</script>
I still think last one inline <script> should be there and it is not mixing logic with representation because this is component - solid piece. It have no meaning one without another. Actually this should be a part of application. Something like html of component(in las one example is div) should be defined and wrapped with component which will automatically add script and ids.
Now. I showed you 2 examples and i will explain why second is too specific. All stuff is in accessibility and performance(and memory leaks). If you will refresh all html of component frequently - it will blink, also you will need to set up all dynamic events back and check everything for memory leaks. But the main problem if JS will fail - your application will show nothing.
So i prefer to have choice between those two:) and use everything on their places.
Check out a site called quince. I am not sure how many patterns here are javascript ui patterns. But this is a pretty good resource for ui patterns
Patterns aren't always language agnostic. A lot of classic design patterns are pointless in JavaScript because we don't need a lot of the workaround that they solve in stricter langauge paradigms.
The reason MVC isn't such a hot fit for client-side web development, however is more situational.
First of all I think time and pain have proven that typical web applications are best treated as two separate applications. The one that happens on the browser and the one that happens on the server. The fewer dependencies you establish between the two, the more flexible, maintainable and easier web apps have been to modify in my experience.
The M is business logic (which people tend to incaccurately conflate with "database layer" IMO).
The problem with MVC in that scenario is that we don't want to expose business logic on the client-side and attempting to munge the whole app into one hideous http-divide-hiding construct has proven painful as I mentioned.
Very similar patterns where you separate data or "view model" concerns can work fairly well, however.

Categories