AngularJs SPA Javascript file - javascript

Do i have to include all my javascript file while loading main index page?
In single page application when we are not logged in, we include all of our .js file in main index file. This contains js file that is only needed when users are logged in.
What is better approach of managing angular app in this context?

Simple answer: yes.
Your application is a single-page one, so you can combine all JS files into one and load it at one request. It saves time for processing in the future.
Alternatively, create two pages login.html and others.html, then load two different sets of JS files accordingly.
Normally, nowadays the bandwidth is not the bottleneck, loading a larger JS file does not make trouble (usually).

You can split your code into multiple modules and then just load the js needed for that module.
I suggest using Gulp with packages to inject HTML when appropriate. You then have single lines of code as place holders for your Javascript and you run the Gulp task to inject the Javascript into the areas where it is needed.
You could also run gulp tasks to minify your js into just a few minified files. You will need to be sure your js in min safe (gulp can do this too).

If you make AMD - most often using RequireJS - then you won't need to include all from the very beginning.
A while ago we did a similar project, although without AngularJS, and by using RequireJS we made the different pages, which use different files. And this way people's browsers will never download certain files if they never go to certain pages.
(Of course, we had many pages inside the app, not just 2 or 3, where this wouldn't make any difference.)

Related

Webpack - multi-page application with a single budled js file

I'm trying to update a legacy frontend web application to use webpack for the dependencies. Right now it's structured like so:
- login.html
- dashboard.html
... src/login.js
... src/dashboard.js
Each page has its own javascript file, plus it loads in a bunch of external dependencies via script tags on the page. My problem is that most of the pages use some variation of the same bunch of very large libraries and jquery plugins. If I bundle each page's js into a seperate js file, i'm going to end up with a huge bundle for every page that has to be downloaded every time the user changes page. I'd prefer to just have one bundle that every page loads and uses the neccessary part. Is webpack fir for purpose here, and if so how should I be going about it?
I "solved" this by keeping my library imports as they are, ie jquery, bootstrap etc downloaded from CDNs. I made one bundle for each of my bigger local libraries and included that on each page so that it gets cached by the browser, then I used webpack with multiple entry point for our bespoke js code.

Split very large javascript file

I'm working on a web project that uses webgl content generated with unity. When trying to load the required js files the browser freezes for around 30 seconds. The main js file has 35MB size unzipped so this seems to be the cause.
I want to avoid this freeze if possible but I couldn't manage to do it using WebWorkers since the script needs access to UI. My other possible solution is to try to split the js file into smaller ones but I don't know how to do it. Do you have any suggestions?
If you add async to your script tag like this <script async src="app.min.js"></script> it will not block rendering anymore. Also caching the script in the browser or delivering it from a CDN can help reduce the download time.
35MB are, however, way too much for a website. Are you sure there isn't a lot of unused stuff like libraries in it?
We recently wrote an article with web performance best practices, with explanations to critical rendering path and other fronted concerns here
35 MB just for the JS file seems ridiculous. It could be that the entire build is probably of that size (textures, media, etc.). Have a look here on how to reduce the build size.
Though 35 MB is wayyyy to much for a JS file, you can start by following pointers:
Create utilities and reuse the code. This can be at any level. Be it generic component (HTML generating code) or validation logic, if it can be configured using arguments, make a function and use it.
If you have Hard-coded JSON in your js, move them to .josn files and load them only when they are required.
Split files based on sections in view. In SPAs, there are cases when a section is not visible. For such cases, don't load such files. Spread your code base from 1 file to 100s of file.
If you have a lot of event listeners, move them to different file. You can have section_event.js, section_data.json, section_utils.js and section_index.js. If there involves lot of data parsing, you can even have section_parser.js
Basic Idea is to split code into multiple files. Then, make code more reusable. You can even look into loading libraries to reduce your load.
Also, load a resource only when required. SPA have stages. Load concerned files when they are needed. Split download from 1 time to partial, on-demand approach. Also look into webpack or grunt or gulp to minify js.

What to do if JS file size grows too big [duplicate]

What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.
Our JavaScript code is roughly "namespaced" as:
var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and variables */
},
orders: {
/* 100's of functions and variables and subsections */
}
/* etc, etc for a couple hundred kb */
}
At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes forever to find anything in the JavaScript code and the browser still has a dozen files to download.
Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices?
The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and others). Alternatively you can group your JS into application functional areas if that's easier for you to navigate.
If you put all your JS files into one directory, you can have your server-side environment (PHP for instance) loop through each file in that directory and output a <script src='/path/to/js/$file.js' type='text/javascript'> in some header file that is included by all your UI pages. You'll find this auto-loading especially handy if you're regularly creating and removing JS files.
When deploying to production, you should have a script that combines them all into one JS file and "minifies" it to keep the size down.
Also, I suggest you to use Google's AJAX Libraries API in order to load external libraries.
It's a Google developer tool which bundle majors JavaScript libraries and make it easier to deploy, upgrade and make them lighter by always using compressed versions.
Also, it make your project simpler and lighter because you don't need to download, copy and maintain theses libraries files in your project.
Use it this way :
google.load("jquery", "1.2.3");
google.load("jqueryui", "1.5.2");
google.load("prototype", "1.6");
google.load("scriptaculous", "1.8.1");
google.load("mootools", "1.11");
google.load("dojo", "1.1.1");
Just a sidenode - Steve already pointed out, you should really "minify" your JS files. In JS, whitespaces actually matter. If you have thousand lines of JS and you strip only the unrequired newlines you have already saved about 1K. I think you get the point.
There are tools, for this job. And you should never modify the "minified"/stripped/obfuscated JS by hand! Never!
In our big javascript applications, we write all our code in small separate files - one file per 'class' or functional group, using a kind-of-like-Java namespacing/directory structure. We then have:
A compile-time step that takes all our code and minifies it (using a variant of JSMin) to reduce download size
A compile-time step that takes the classes that are always or almost always needed and concatenates them into a large bundle to reduce round trips to the server
A 'classloader' that loads the remaining classes at runtime on demand.
For server efficiency's sake, it is best to combine all of your javascript into one minified file.
Determine the order in which code is required and then place the minified code in the order it is required in a single file.
The key is to reduce the number of requests required to load your page, which is why you should have all javascript in a single file for production.
I'd recommend keeping files split up for development and then create a build script to combine/compile everything.
Also, as a good rule of thumb, make sure you include your JavaScript toward the end of your page. If JavaScript is included in the header (or anywhere early in the page), it will stop all other requests from being made until it is loaded, even if pipelining is turned on. If it is at the end of the page, you won't have this problem.
Read the code of other (good) javascript apps and see how they handle things. But I start out with a file per class. But once its ready for production, I would combine the files into one large file and minify.
The only reason, I would not combine the files, is if I didn't need all the files on all the pages.
My strategy consist of 2 major techniques: AMD modules (to avoid dozens of script tags) and the Module pattern (to avoid tightly coupling of the parts of your application)
AMD Modules: very straight forward, see here: http://requirejs.org/docs/api.html also it's able to package all the parts of your app into one minified JS file: http://requirejs.org/docs/optimization.html
Module Pattern: i used this Library: https://github.com/flosse/scaleApp you asking now what is this ? more infos here: http://www.youtube.com/watch?v=7BGvy-S-Iag

Should pages that are included in other pages have their own script?

I am using RequireJS and I am creating a own script file for each page. However I also have some components that are included into some of the pages (server side). Should these pages also get their own script file, or should the necessary javascript be in the containing page? Some of the functionality for the included pages are common to many pages.
I think you'd be better off thinking about your javascript as reusable modules rather than page-specific functionality. So, say your page has a search box which initiates an AJAX request, a few date pickers, and a whole bunch of tabs. Each of these should be a module (or if the functionality they provide is complex enough, a few modules). By breaking down your app into small pieces that have very focused aims, you make it easier to test each bit in isolation (automated unit tests) and reuse the functionality elsewhere.
Now as to how to load your javascript modules, there's a point where it makes sense to strategically load stuff based on user needs (ex: core.js is loaded by default but search.js isn't loaded until the user accesses the "search" tab) but you can get pretty far just packaging everything into a single file (require's r.js tool does this for you) and using the same script file (main.js) on every page.
When using a single script file, keep in mind that your js will need to work when the target of it's functionality is not present. jQuery makes this super simple and you almost don't have to think about it - ex:
$('#js-foo').on(...) // <-- this doesn't blow up if '#js-foo' isn't on the page.
I've also seen people set a data-attr on the body tag for the page - e.g. data-page="foo" and key js off of that:
var page = $('body').data('page');
if (page === 'foo'){
component1.setup();
component2.setup();
}
In your case, I would try building everything into a single file using RequireJS / AMD-style modules. Each component would get its own module file (mycomponent.js), your main.js would require() all your modules and init things appropriately, and finally you'd configure your r.js build to package everything into a single file when deploying to / running in production.
If you are interested in exploring this topic more, check out these posts:
Single Entry Point FTW
Single Entry Point Redux

Best practices for managing and deploying large JavaScript apps

What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.
Our JavaScript code is roughly "namespaced" as:
var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and variables */
},
orders: {
/* 100's of functions and variables and subsections */
}
/* etc, etc for a couple hundred kb */
}
At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes forever to find anything in the JavaScript code and the browser still has a dozen files to download.
Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices?
The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and others). Alternatively you can group your JS into application functional areas if that's easier for you to navigate.
If you put all your JS files into one directory, you can have your server-side environment (PHP for instance) loop through each file in that directory and output a <script src='/path/to/js/$file.js' type='text/javascript'> in some header file that is included by all your UI pages. You'll find this auto-loading especially handy if you're regularly creating and removing JS files.
When deploying to production, you should have a script that combines them all into one JS file and "minifies" it to keep the size down.
Also, I suggest you to use Google's AJAX Libraries API in order to load external libraries.
It's a Google developer tool which bundle majors JavaScript libraries and make it easier to deploy, upgrade and make them lighter by always using compressed versions.
Also, it make your project simpler and lighter because you don't need to download, copy and maintain theses libraries files in your project.
Use it this way :
google.load("jquery", "1.2.3");
google.load("jqueryui", "1.5.2");
google.load("prototype", "1.6");
google.load("scriptaculous", "1.8.1");
google.load("mootools", "1.11");
google.load("dojo", "1.1.1");
Just a sidenode - Steve already pointed out, you should really "minify" your JS files. In JS, whitespaces actually matter. If you have thousand lines of JS and you strip only the unrequired newlines you have already saved about 1K. I think you get the point.
There are tools, for this job. And you should never modify the "minified"/stripped/obfuscated JS by hand! Never!
In our big javascript applications, we write all our code in small separate files - one file per 'class' or functional group, using a kind-of-like-Java namespacing/directory structure. We then have:
A compile-time step that takes all our code and minifies it (using a variant of JSMin) to reduce download size
A compile-time step that takes the classes that are always or almost always needed and concatenates them into a large bundle to reduce round trips to the server
A 'classloader' that loads the remaining classes at runtime on demand.
For server efficiency's sake, it is best to combine all of your javascript into one minified file.
Determine the order in which code is required and then place the minified code in the order it is required in a single file.
The key is to reduce the number of requests required to load your page, which is why you should have all javascript in a single file for production.
I'd recommend keeping files split up for development and then create a build script to combine/compile everything.
Also, as a good rule of thumb, make sure you include your JavaScript toward the end of your page. If JavaScript is included in the header (or anywhere early in the page), it will stop all other requests from being made until it is loaded, even if pipelining is turned on. If it is at the end of the page, you won't have this problem.
Read the code of other (good) javascript apps and see how they handle things. But I start out with a file per class. But once its ready for production, I would combine the files into one large file and minify.
The only reason, I would not combine the files, is if I didn't need all the files on all the pages.
My strategy consist of 2 major techniques: AMD modules (to avoid dozens of script tags) and the Module pattern (to avoid tightly coupling of the parts of your application)
AMD Modules: very straight forward, see here: http://requirejs.org/docs/api.html also it's able to package all the parts of your app into one minified JS file: http://requirejs.org/docs/optimization.html
Module Pattern: i used this Library: https://github.com/flosse/scaleApp you asking now what is this ? more infos here: http://www.youtube.com/watch?v=7BGvy-S-Iag

Categories

Resources