Formatting a file is important as you develop, but it means nothing to the web server but extra bytes to load. Formatting makes it easy for you to decipher code and keep it organized, but this formatting is only important to you, not the web server. The bytes that store this formatting can be removed after you’re done developing, which reduces processing time. By minifying your code, you remove extra formatting such as spaces and tabs. You would still use the formatted documents for edits, but the web server would load your minified one in production.
Here are a few places to help you minify JS:
- Avoid Nested Loops
This is true for just about any language. Nested loops are difficult to process, and many times they lead to logic bugs. You can usually avoid nested loops by creating functions to process data. It’s also beneficial, because functions are reusable code that you can use in other parts of the application.
- Cache Scripts including CSS
- Place JS Files at the Bottom of Your HTML Pages
It’s tradition to place your script and CSS file links at the top of your HTML pages. When the browser loads the page, it first loads the top of your pages and then the body content. When you place JS files at the bottom of your HTML pages, you improve the page’s perceived speed. Perceived speed is the illusion that the page is loading faster than it really is, and it can increase customer engagement. Normally, when JS is included at the top, the browser waits for JS files to load and then loads the body. With links at the bottom, the content loads first and then the JS files. The user sees content faster and starts browsing while the JS files load. Your page still loads in the same amount of time, but the perception is that it loads more quickly.
- Don’t Use the ‘With’ Keyword
Microsoft explains the problem with using the “with” keyword. Using the “with” keyword complicates the scope chain, because the JS engine pulls in all properties and methods for the newly defined variable. You probably won’t use all properties and methods, so it adds extra processing for no reason. With more complexity comes longer processing times. Microsoft suggests being more verbose with your code, which means typing a variable each time you want to use its properties and methods. The “with” statement is a handy shortcut, but avoid using it if speed is an issue with your site.
- Always Use “var” to Define New Local Variables
Another tip from Microsoft is to always use var in front of your local variables. Take the following code as an example:
myvar = GetMyVarValue();
- Minimize HTTP Calls