Load view-specific JavaScript in Node.js Express application - javascript

I have web application with multiple views that share the same JavaScript but every view also have its own Javascript. It looks something like:
<!-- html up here -->
<script src="/src/js/bundle.js"></script>
<script>
// some view-specific Javascript
</script>
This ended up mixing my view file (HTML, etc) with my javascript and I'm not sure if creating and loading and external javascript file for each view is a better way.
What is the best approach to achieve do this?

A lot of it depends on how big your page specific js files are. If they are fairly small and most of the useful js is in your bundle, just make one bundle for all pages. If you have a lot of page specific js, you can either just include a second file along with your bundle, or you can create a different bundle for each page so that you only have on script tag on each page. Here is another thread on the issue, including a useful gulp script to automate the creation of multiple bundles

Related

How to load javascript files dinamically on server side rendered website?

There is a website with a lot of javascript files. Website uses no framework just webpack, jquery and other plugins which are installed through npm. Just simple html site and laravel for backend.
All javascript files are required to main.js. And main.js files is added to template html file.
How to load for each page only files that are needed for that page? For example if you visit contact us page client should load only contact.js file without other files like products.js, register.js and etc.
Ofcourse I could include each js file to its page without loading all js files in one file. But maybe there is smarter way how it could be implemented on my situation from javascript and webpack side?
Now my javascript file size is 2mb, some pages needs only small part of it. So, I need for each page load only what is needed for it.
If it is a classical server, then I don't think it's possible. With a Javascript library like React, you could've considered code splitting.
I think your initial approach, which was splitting them into their respective .js files is, as it stands now, the best approach
May you use RequireJs ? It will optimize your Code &' Performance

Does creating javascript dll have any advantages over adding it directly using script tag?

I am working on project with larger javascript files.I can add these javascripts in one of the two ways.
1) create a separate class library project and have the javascript files there as embedded resource.Include a reference of the dll into the web project and then include those using scriptmanager as webresource.
2)Have these files in a separate folder and then simply add these files using the script tag and there path.
I am not going to paste the javascripts in my page within the script tag cause they would mess my pages mark up.
So I would like to know which one is better of the above 2 ways.In either of the 2 ways everytime i load the web page i see GET request for the js files.If i create a javascript dll will the browser cache it?
You can't create "javaScript dll". JavaScript is a client-side stuff, dll is server-side. No matter in which project your javaScripts are, it will still be sent to the client and executed there. So it makes no sense to put JS files to another project (especially as resources)
We usually want to minify and bundle the JS files, so the client will do less requests to the server and also to reduce the amount of data to transfer.
For minifying the JS files I would recommend to use Web Essentials extension to VS. It is very handy and can make web programming easier.
Minification will remove all unnecessary characters from the JS file and it will also reduce the length of the identifiers (like method names and variable names).
You can learn about bundling here. It is useful when there are more JS files to load to load all of them at once.

Can you use multiple .JS files when developing a complex Javascript application?

Coming from a C# background where every class is (best practices) stored in its own individual file, it makes development quite clean. I've never written anything complex in Javascript in the past, but I am starting to learn HTML 5 and I want to write a complex game using the HTML 5 canvas.
Putting all of my functions and code into a single .js file seems very messy. Is there a way to split it up, or a tool/IDE that lets you develop using separate files and compile them into a single one for deployment?
I guess I am looking for some best practice advice. Questions like this generally seem to get closed, so here are my specific questions to adhere to the SO FAQ that demands practical, answerable questions:
Does complex JS development usually involve all the code being in a single JS file? Eg. you're writing space invaders, do you just have spaceinvaders.js or do you have ships.js, logic.js etc.
Is it possible to split up your JS (whether using multiple script tags or pre-compiling to a single JS file) or to just put it all in a single file?
What's the industry standard? Does the HTML 5 spec make any recommendations?
There two possible ways.
Personally, I would use a build tool to simplify working with multiple files.
Using a build tool
Grunt
My favourite tool to keep up with complex js applications is grunt. With grunt you can develop in as many files as you want and use its plugins watch and concat to automatically concat them on save. You can do a lot more but this is the basic use case which may be helpful for you.
Grunt requires nodejs and takes some time to setup. But once you are ready with your Gruntfile setup it really speeds up your development process.
To make your project ready for production use you can also minify your scripts with some configuration and a single command.
A lot of the major javascript libraries are using grunt, easily recognizable based on their Gruntfile: jQuery, AngularJS, Twitter Bootstrap etc.
Grunt is also part of the development toolset yeoman.
Brunch
Brunch is another build tool which allows you to do similar things like grunt does.
Loading only the needed files
If you are developing a huge single page application and are concerned about the startup time of your application, one single file may not be the best solution. In this case you can use a javascript module loader.
Require.js
Therefor require.js is a goot fit. It allows you to only load the actual needed files on the current page. Though setting up require.js is a bit more work than setting up grunt.
Of course you can use more than one javascript file. How else would libraries like jQuery or Knockout function?
One thing to keep in mind, though, is that one of the things you want to do to keep your pages feeling snappy is to reduce the total number of http requests per page load. Adding a bunch of javascript files that are loaded separately causes an additonal request for each extra file. Therefore, you might want to experiment with a system for your build that stitches your javascript files together into a single item that you can use at deployment. There are a number of solutions out there that will do this for you in an automated way.
you could consider using requirejs - a very nice libray to split your javascript to modules.
it also provide a tool that you can "combine" all modules to a single file.
You can use as many javascript files as you want. Just add a link to them in your html code:
<body style="background-color: black" onload="main();" >
<!-- Your HTML body contents -->
<!-- Your scripts (here, I used HTML5 BoilerPlate to setup, and the links to jquery are provided) -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="js/main.js"></script>
</body>
Then you can hookup your main.js to listen for the main() function call:
function main() {
//here you can do your basic setup or delegate the control of the app to a different .js file.
}
or the jQuery document ready callback:
$(document).ready(function() {
//here is a good spot to hookup other jQuery listeners
});

Where to store HTML templates for use in Backbone.js

I'm currently developing a static site (no backend or server stuff) with Backbone.js and Middleman. The site doesnt have any dynamic content, just plain html code. But it has some transitions between pages and some Javascript effects.
So I want to make use of Backbones Router for the history and want to append the views dynamically to the DOM with Backbone views. So far so good.
Now I was wondering where to store the HTML parts of the site, so that Backbone can use it. With Inline script tags I think it gets too messy, so I want to swap it out in different HTML files. Now I could dynamically load the HTML files via requirejs, but I think it would be better to pack all the HTML stuff in one JS file and load it the first time someone visits the page.
How could something like this be done? Or does anybody have a better solution?
If you are developing a HTML5 application, then you can use application offline cache to fetch all the necessary HTML files and other resources. It involves writing a cache manifest file.
The following website provides a nice description of the offline feature and writing the manifest file: http://diveintohtml5.info/offline.html.
Personally I seperate all the parts of backbone in different folders. So for the templates I put each and one of them in a seperate files in a template folder. That way while developing everything is clean. I load them by using "text!" functionality in require.js.
When I want to put the project in development I use the optimization part of require.js which minifies and combines all the files for me.
Hope that helped.
After a lot of researche, I'm doing it this way:
Store templates as .jst.ejs in template folder
include them with Sprockets
use JST to load the templates
In backbone I use the views class to extend new views and use the templates:
App.Views.Layout.Logo = Backbone.Views.extend({
template: JST['templates/layout/logo'],
el: "#logo",
});

MVC - is there a nice way to bundle controls with their respective javascript?

I'm pretty new to MVC and I can't decide on the best way to store cshtml files and their respective javascript code. Some JS code in my project needs to run globally, but most of it is entirely tied to specic views or partial views.
If I put the javascript in the views, I get a mess of inline uncacheable javascript, if I put it in one central file, I lose modularity.
I heard that in MVC4 there are going to be minification features, is there something I can do with MVC3 that will allow me to choose in the Views which javascripts to include and then group them and minify them automatically? (maybe even in groups?)
Cassette it's essentially the same thing as the upcoming MVC4 bundles.
In your view page, you can reference scripts and stylesheets using Cassette's Bundles helper class.
#{
Bundles.Reference("Scripts/jquery.js");
Bundles.Reference("Scripts/page.js");
Bundles.Reference("Styles/page.css");
}
<!DOCTYPE html>
<html>
...
In addition, Cassette has native support for Less and CoffeScript. It has also support for HTML Templates, if you are interested in client side MVC frameworks like Knockout.js or Backbone.js.
Still you have to choose how to group your content. As the official documentation is suggesting, probably the best choice is to treat bundles as units of deployment.
Keep in mind that a bundle is a unit of deployment. If any asset in a bundle changes, then the entire bundle has to be downloaded again by web browsers. So perhaps group shared code into a bundle and put page scripts into their own bundles.
You can put the javascript in separate files, for each view. Then in the _Layout.cshtml enter a #RenderSectionto the head:
<head>
<script src="#Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
#RenderSection("head",false)
</head>
Then in each view, you can put a section that will be rendered into the header:
#section head{
<script src="#Url.Content("~/ViewScripts/Order/New.js")" type="text/javascript"></script>
}
You'll want to use a method like this:
http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/
See this post:
Using Rails 3.1, where do you put your "page specific" javascript code?
It is not a best practice to use script in partials (in my point of view)
is suggest you to write partial specific script to separate js and bind events on page load or if partial was loaded via ajax then on success event.
then you can be sure that events are not bound multiple times and view is just a view
#Anders approach is good if you require the scripts to be in the head tag. But I find that most times it is not required if it is page specific JavaScript. You can put your script tags that reference your script files wherever they are required in the View. Automatically bundling and minification will be supported in ASP.NET 4.5. Until that time you can integrate yuicompressor into Visual Studio.

Categories