Reusing HTML code with only client side technologies - javascript

I am tasked with creating a website using only client side techs such as HTML, CSS and JavaScript. We can't using any server-side tech because the instructor is too lazy to install anything and won't allow us to deploy using something such as Heroku. Is there a way I can do this? In particular I want to create partials for that navigation and footer without having to copy and paste them in every single file.

I know of two different approaches:
1. Using Ajax
You can use ajax to do this - probably with the help of a JavaScript library or framework.
JQuery's load can do things like $('#header').load('header-partial.html');
If you're building something more complex with a lot of views, etc... I'd consider using a MV* javascript framework like Backbone.js or AngularJS.
Check out the AngularJS seed project on GitHub for an example
2. Using a build script
If your site is simple enough that all you want to do is include a header and footer on each page, you should consider doing this as a build step in your deployment process. I.E. complile your html with the partials locally, and upload full pages, with the header/footer code on every html page.
This approach has the benefit of not breaking your site if js is disabled.
For an example, check out html5boilerplate's ant build script

Related

How to work with hybrid webapp (MPA and SPA combined)

What are good practices about building a multiple page application using modern JS frameworks?
Multiple page application
In multiple page application we have multiple templates using some “template syntax” to provide us with backend data and AJAX (if needed) or advanced UX voodoo is often handled by jQuery.
Single page application
In single page application “backend data” is provided by AJAX requests and whole routing, frontend logic is handled by JS. We often use some JS framework like Angular or React and compile our sources with task runners/bundlers like webpack or gulp.
Hybrid application
But the most popular around the web seems to be hybrid app. What is typical build workflow while working with such an app? I could not find any tutorials or guides.
So to be specific. I imagine webapp where in which, each page has to be compiled and could share some resources. Every page has own JS routing like wizards or subcomponents. Data is loaded both during page load and AJAX.
For example my webapp would have 3 pages:
guest page - would provide website user with limited content and attract him to sign up
user - would provide signed website user with full content, resources would be extended guest content
admin - shares only styles and webapp “core”
Task Runners/Bundlers
For example in webpack is there a way to specify multiple entry and output points? Maybe the better way is to have multiple webpack/gulp configurations. In that case If I have a lot of pages I would have to write webpack/gulp configurations for every page even though some of them could be exactly the same. How to run that kind of build?
Sharing resources
Will browser load cached js bundle with the same hash like bundle.a2k4jn2.js within the same domain but different address? If so, how to specify such a behaviour in tools like webpack or gulp. I heard about CommonsChunkPlugin but not sure how to use it or even I’m looking at right direction.
Templates
What if I want to load some “backend” data not by AJAX but at the page loading. Of course every templating engine provides us with ability to write native code directly in html template like JSP or PHP. But what if some routing is handled by JS and “template tag” is not visible for page at initial loading i.e. template would not be compiled. Sometimes template engine in server and client could have the same special tag like Blade and Angular which can lead to conflicts.
Directory structure
I suppose that in hybrid app frontend and backend will be tightly coupled. Sharing JS in hybrid app could lead to very complicated imports (in es6 or html script tag). How to keep it simple.
Deploy
What about deploying an application? In java it’s easy because we just specify directories (compiled pages) in build tool (maven, gradle) which be copied to jar/war, but in PHP source code is not compiled how to keep “js source” away from production I could not imagine sensible resolution other than writing own batch/bash script
Summary
I have mentioned specific technologies and frameworks. But my question is about common approach to work with such an webapp rather than “how to do sth in that tool”. Although code examples would be greatly appreciated.
Their is a lot in this question, as a starting point you can define multiple entry points in webpack.
https://webpack.js.org/concepts/entry-points/
If you want to mix data loading between FE and BE then you really need to write an isomorphic JS application and use Node as your BE, otherwise you’ll end up writing everything twice in different languages and having once come across a project like that, trust me you really want to avoid that.
The other bit of this question on shared resources is best answered by WebPack’s bundle splitting which is made for what is being asked here
https://webpack.js.org/guides/code-splitting/
Not sure if I totally understand the question, but single-spa (yes it's redundant) is a tool that can be used to combine multiple apps (even if they are different frameworks) into one single page application. Link to the docs: https://single-spa.js.org/docs/getting-started-overview

vuejs templates als asp.net partialviews, good practice?

i'm using Vue.js in a Website and added the templates in the html Code and the js-Code in a single js-file.
So i do not want to use the *.vue <-> Vuefy/Browserfy approach but bundle and minify my js-files later.
As i have to use Asp.Net MVC i could use split the single Html-file in a view and insert the vue-div-elements hierarchically structured with #Render.Partial(...).
This way i could do a clean separation and use the same system like the *.vue files.
Would this be a good practice?
Do you think it would be better to write the html and new Vue({}) in every partial .cshtml or just write the html code there and put the javascript into (a) js-file(s).
The js-code in script-tags could not be bundled and i don't like that much inline Code but it would a nice coupling of the components code.
By using multiple js-files i could store then in the views folder next to their partial partners and bundle them together with the VS Extension Bundler and Minifier.
Are these thoughts usefull or is there still a good aproach for using vuejs templates in asp.net?
EDIT: I used to write some of the partial views with a specific Preifx. The include inline script tags, wich comes the .vue approach very close and is cool in small components because its all in one page. The inline script is conditional with Razor, so only in the dev build it gets rendered inline, for production it get's send separated. To do so I wrote a powershell script and execute it as pre-build event to exctract all the inline code into a js-file.
This file get's bundled with the other js-files and is served minified for production. So i can use all the Razor features in the html/templates and other pages of the project are just *.cshtml views.
For only-one-SPA-sites the approach mentioned by iknowitwasyoufredo sounds better.
If you use vue.js to do some simple js tasks, instead of jquery I think it is good.
But if you want to have a single page application, routing, two way binding etc. mixing asp.net mvc views with vue.js is not a good idea. Eventually, you will face many problems.
It's an architectural decision but you could implement web api services with dotnet, and use this services from a node.js application (express, webpack, vue.js).

React.js server side rendering with PHP

I would like to develop themes/plugins for WordPress based on React. To make it search engine friendly, I need it to be rendered initially on the server (serverside-rendering).
The only way to do this, as far as I know, is to use react-php-v8js, which requires the PECL V8js extension. This is a problem since I have no control over the platform on which these themes/plugins will be run.
Is there a way to make React and WordPress work together without having to install additional extensions? Perhaps by building/compiling React files into PHP?
There's an article that describes how to do this:
https://sebastiandedeyne.com/server-side-rendering-javascript-from-php/
But it's a fairly complex setup and it requires using composer. That can be difficult in Wordpress projects since Wordpress tends to completely eschew the modern php architecture.
If you're looking for a library to help with SSR in PHP:
https://github.com/spatie/server-side-rendering
Best of luck on it.
If you want your content to be indexed by search engine without js, you can print your minimal content using Wordpress, just the bare minimum + crucial meta tags, maybe localize some initial state for your react app to boot. A bare bone theme such http://underscores.me/ would be sufficient. When js is available, you can replace your whole WordPress generated content with React ones.
The ideal one is to have React generate the content for you. But it's hard until we can see that nodejs / PECL V8js extension available everywhere.
If you can at least install nodejs and launch a node process then it should be ok, although not so simple.
You would need to generate a ssr version of your assets and use it in a node process that would listen on a socket to write the html result..
In your controller you can create a socket to your node process (something like stream_socket_client(...)) and then you can send a dummy function written as a javascript string to that socket (something like stream_socket_sendto($sock, "getResultForMyWidget(someParams){...}")). That function would be evaluated in the node process that would return the response to the controller (the html response as a ReactDOMServer.renderToString from the component you want to render).
That's it for the big picture.
There is a symfony plugin that illustates it very clearly (see this github) and comes with a dummy server node process to illustrate how it handles the socket listening and eval of the incoming function and returns the html result. See also the example in the sandbox for a bigger picture and in depth implementation. You should be able to adapt it to wordpress.

Client-side solution similar to asp.net master page

I recently started using WebStorm to implement web applications and find the experience much better than using Visual Studio.
I am considering moving the "view" part in mvc to pure html as much as possible without relying on server template engine such as Razor. So that I don't have to open visual studio until server side code is needed.
Google results showed that client side template engines such as Handlebars and Mustache will be able to help generate dynamic html pages. One thing I have not found is that ability to combine "parts" of pages together (like the master page in asp.net) so that we don't need to copy/paste header/footer everywhere.
How do I achieve "master page"-like functionality with client side (i.e. javascript) solutions?
Thanks for your help.
You could try this:
use 'shtml' file to struct your webpage,so that you can reference the include instruction:
<!--#include file="head.html"--><hr><b>Hello,this is body!</b><hr><!--#include file="foot.html"-->
As to 'head.html' and 'foot.html',well,you know what should include in them.Actually,they are 'div' segments~~~

Very large single page application design problems

I am currently writing whats going to be a very, very large single page web/javascript application.
Technologies I am using are ASP.NET MVC4, jquery, knockout.js and amplify.js.
The problem I am having is that most if not all of the single page application examples are for smaller applications where having all of the script templates (be it jquery, handlbars, etc...) are all in the same file along with the rest of the html code. This is fine for smaller apps but the application I am building is an entire maintenance logistics application with many, many, many screens.
The approach I took so far is I have an outer shell (my main index.cshtml file) and I am using jquery's load() method to load or rather inject the particular file I need when a user makes a certain selection.
example:
function handleLoginClick(){
App.mainContentContainer.delegate('#btnLogin', 'click', function() {
App.loadModule('Home/ProductionControlMenu', App.MainMenuView.render());
});
}
here's the code for the App.loadModule function:
App.loadModule = function(path, callback){
App.mainContentContainer.load(App.siteRoot + path, callback);
};
All was going well until I needed to actually start interacting with the various form elements on the newly loaded screen. jquery can't seem to get a handle on them directly. I can't use .live() or .delegate() because they aren't events, they are textboxes and buttons and sometimes I need to change their css classes.
They only way I found is to get a handle on an element from the outer shell (something that wasn't loaded via .load() ) and use jquery's .find() method like so:
App.mainContentContainer.find('#btnLogin').addClass('disabled');
clearly I don't want to have to do something like this everytime I need to interact with or even retrieve values from a form element.
Does anybody have any ideas as to how I can create a maintainable very large single page application with potentially hundreds of .html files without having to have all that html code located in a single file and still get around this .load() issue I am having?
Any thoughts would be greatly appreciated. :-)
V/R
Chris
UPDATE
I thought I'd post an update and as to how things went and what worked. After much research I decided to go with Google's AngularJS Javascript framework. It simplified the ordeal exponentially and I would definitely, definitely advise all who are looking into making a large SPA to give it a look.
Links:
Main Site
http://angularjs.org/
Awesome free short videos on Angular:
http://www.egghead.io/
This is actually a very complicated question as it really gets down to the design of your architecture.
For large-scale single-page applications, it's best to use some sort of front-end MV* style framework such as backbone.js, which ties in to jQuery quite usefully. You should also think about using some sort of dependency management framework such as require.js in order to load your scripts and dependencies asynchronously, and even better -- use the AMD pattern in your application design to make your architecture modular and easier to manage.
As far as how this relates to your MVC4 project, you have some options:
Do you want to use MVC as a "service layer" of sorts, that simply returns JSON objects, allowing your front-end to do the markup/template creation (think handlebars.js), or
Do you want your MVC project to return partial views (HTML) as a response, where you leverage the Razor templating system and simply use the front end to display what comes back from the server?
Either way, you will have to devise a way to handle front-end events and navigation (backbone provides both of these things when coupled with jQuery). Even more complicated is the pattern you choose to notify one view of another view's activities (there are many ways to do this) -- a publish/subscribe pattern for example.
I hope I have helped a bit, I know I'm not fully answering the question, but the answer could get really long!
Lots of things are wrong with your approach. What I'd recommend is to watch some presentations on how people build Single Page Applications and what tooling is mostly used.
This seems like something reasonable: http://singlepageappbook.com/
You will at least want
some kind of modules system (I recommend AMD – http://requirejs.org)
an MV* framework (Backbone, Ember.js etc.)
DOM/AJAX Framework (jQuery, Mootools etc.). Some frameworks offer this and all of the above (Dojo, YUI, Sencha)
build solution (to have different environment in development / production)
Couple of good links:
http://nerds.airbnb.com/slides-and-video-from-spike-brehms-tech-talk
http://video.copenhagenjs.dk/video/3413395/simon-hjberg-swipely-building
http://backstage.soundcloud.com/2012/06/building-the-next-soundcloud/
http://www.youtube.com/watch?v=vXjVFPosQHw
If you don't need a complicated truly SOFEA Single Page App then I recommend you go the PJAX route.
Then you just write your app as a normal web 1.0 app with the performance benefits of a single page load. I urge you to consider this an option as it allows you to do most of your validation work server side.
The idea is very simple on every response your sending the whole page back minus the header and footer (which contains the javascript and css includes). DOM rendering time is incredible fast these days... whats not is a full page reload, So don't worry about the size of the HTML your returning back.
Also the "PJAX way" is much easier to cache, Google SEO friendly and is in fact what the new Basecamp does.
Note: Wanted this to be a comment not an answer but don't have enough exp to post comments ;(
[any corrections by community members welcome!]
Important points to consider for single page apps:
Lazy loading is vital as you don't want hundreds of js files loaded straight away as user first loads the page (very slow load time).
Good File organisation,- helps making changes easier, reduces complexity a bit and promotes reusable components. Makes testing of components easier.
Testing,- Since single page apps have a lot of javascript going on under the hood you would need a test framework for automatically testing components. This testing is on top of the tests you would use to confirm if certain user controls are rendered etc as you wouldn't want a viewless component making an ajax call to server when it shouldn't etc.
+1 for gryzzly's point about using a framework.
Sencha have a nice MVC like framework for their ExtJs product. They have data stores, ajax, lazy loading, class hierarchies and a lot more all bundled into the package. They have a good api page also to lookup object properties and methods (handy since there doesn't seem to be any intellisense for javascript :/ ). Their api page is; as far as I know, an example of a single page app. I know much of the stuff ExtJs does you can find an open source alternative but I like that it's just the one library and I don't have to download a couple of different frameworks to do various operations. [note: I have no affiliation to Sencha except for being a customer of theirs and like their stuff.]
Conclusion:
I'd say it would be quite difficult to manage a large single page app without using some client side framework; whether open source or not, and without using some architectural pattern like a client side MVC.
Single page apps I think are more complicated so your team would need to be quite handy at understanding the concept of a single page app and how to implement it. If you pull it off the site will be amazing in terms of user experience.
I would recommend to use Sammy.js and split various viewmodels in knockout to a separate url. And if you're using asp.net mvc 4, use partial views (user controls) so that you put all code in one file. And name all and split all js-code in a meaningful way, filename and namespace in js. That will help a lot in maintainability and your own sanity in the long run.
And use common sense!
The way I did it was to include javascript code related to the template along with the template itself. And then load the whole template+script thing using ajax. If you want to try this be warned that most browsers don't execute <script> tags injected into the page. Especially if done using innerHTML. As such you should eval the script tags yourself (alternatively you can use document.createElement to inject the script but this does not offer any additional advantages compared to eval since the browser will blindly execute the script anyway).
In my case, to make it easier to grab the html and script portions of the template I store my templates in XML files instead of plain old HTML. That way I can simply use .responseXML of the ajax request to parse the template. My template has the following basic structure:
<template options...>
<title>Optional</title>
<html><![CDATA[
Template body
]]></html>
<init><![CDATA[
// code that only needs to execute once
]]></init>
<script><![CDATA[
// code that needs to run every time
// the template loads
]]></script>
</template>
You also need to remember to configure your server to reply with the correct content type for you templates. Otherwise resultXML won't work. This is not the only way to implement this system of course. You could simply save your templates as HTML and then parse that HTML to extract scripts to execute.
The main bulk of your code, the functions, constructors, objects etc. can be included in a js file. The template script only need to call those functions to tell the rest of the page how to work with the template.
If you further separate your data from your template and only populate the template with data on the page or make a separate ajax request for JSON data then you can configure your server to make the browser cache your templates. This is especially useful for often used templates (such as templates for dialog boxes). This allows the browser to download the template only once and use the cached version the next time you call the template.
Anyway, that's how I did it last time. It scaled well enough to serve facebook users (the web app was a facebook app). Just sharing my experience. Hope it helps.
I've written a few huge single page application using Dojo Toolkit. I'm pretty sure whatever JavaScript framework you choose will probably work for you. I use Dojo because it provides me with features that makes huge single page application development easier to manage.
You can use Dojo's widget system to help you define all your screens and forms as widgets and then when you need them you can just instantiate and insert them wherever you need it. When ever you want to get rid of it, you can simply call destroy or destroyRecursive on that particular widget and its gone. Dojo's widget system also help you separate your HTML from your JavaScript, but still keep it together so that they are not located all over the place.
I've include a simple widget definition for a Login form.
This is the HTML template.
/* mine/forms/Login.html */
<div>
${form_name}
<label>Username</label>
<input data-dojo-type="dijit.form.TextBox"
data-dojo-attach-point="_usrfld" />
<br />
<label>Password</label>
<input data-dojo-type="dijit.form.TextBox"
data-dojo-props="type: 'password'"
data-dojo-attach-point="_pwdfld" />
<br />
<input data-dojo-type="dijit.form.Button"
data-dojo-props="label: 'Login'"
data-dojo-attach-event="onClick:_handleLogin" />
</div>
This is the JavaScript portion for the widget.
/* mine/forms/Login.js */
define([
"dojo/_base/declare",
"dijit/_Widget",
"dijit/_Templated",
"dijit/_WidgetsInTemplateMixin",
"dijit/form/Button",
"dijit/form/TextBox",
"dojo/text!./Login.html"
], function(
declare,
_Widget,
_Templated,
_WidgetsInTemplateMixin,
Button,
TextBox,
template
) {
return declare("mine.forms.Login", [_Widget, _Templated, _WidgetsInTemplateMixin], {
// assign the template
templateString: template,
// signal that we will have widgets within our template and the parser should
// locate them and instantiate them
widgetsInTemplate: true,
form_name: "My Login Form",
// place holders that will be referencing the corresponding widgets
// that I have placed a data-dojo-attach-point on
_usrfld: null,
_pwdfld: null,
_lgbtn: null,
// a call back function that will be trigger when the Login button is clicked
_handleLogin: function() {
var usr = this._usrfld.get('value');
var pwd = this._pwdfld.get('value');
// now you have the username & password
// you can use it to login
}
});
});
There are a few benefits that the widget system provides:
The HTML template will be loaded for you when needed
You can have widgets within widgets. Dojo takes care of instantiating and even destroying those widgets for you
You can use dojo's simple template language to help with inserting strings. The example above uses ${form_name}. If you want to use a more sophisticate facility dojo also supports a Django similar syntax templating language. This will allow you to use most of the tags available with Django like for, if-then-else, etc.
data-dojo-attach-point is very helpful. If you use this, you will never need to assign id to a DOM element anymore. You will not need to locate the element in your HTML DOM tree. The variable you name in data-dojo-attach-point will be auto assign to reference the widget or DOM element you have defined in your template. The example above uses the _usrfld, _pwdfld, and _lgbtn.
data-dojo-attach-event is also very helpful. If you use this, you will not have to manully add an event hook to the button, Dojo's widget system will hook it for you and will also clear the hook when your widget is destroyed.
If you use Dojo's build system, which is a system that takes all your JavaScript codes and compresses them, Dojo will replace your template with the actual HTML so that when you load your widget in production mode, Dojo doesn't have to make another AJAX request to grab your template.
These are just some of the features I use daily when I develop my projects. Hopefully it will provide you with some insight that you can use to make your decision when choosing the proper JavaScript framework for your project. As a side note, I'm not advocating Dojo or anything, just wanted to share what works for me.
To handle large size single page application it's recommended to break the individual module into different apps.
example : apps like search page app and result page app.

Categories

Resources