An ordinary website has 5-15 JavaScript files and several inline pieces of code that can include external libraries. As a result there are 10-20 pieces that can be combined together. The benefits are obvious: faster page load time, customer satisfaction and better DDoS fault tolerance – under attack, every connection, even static, may lead to denial of service.
If you think that you can just put all the JavaScript code into one file, you are going to get upset very quickly. Indeed, most likely that your scripts won’t work when combined into one file. If you are an experienced web developer, you will not probably find it difficult to fix all the problems and make all the code operable. If not – this article is just for you.
So, let’s say we have 20 pieces of code that we need to merge together. We need to make sure that every piece won’t break other pieces. Why? Because if a JavaScipt file has an error, your browser will stop running this file and all your scripts won’t work. At all. What can we do? Fortunately, JavaScript has all the means to handle errors. All we need is the try-catch construction.
This short example will help you combine all your JS code into one script painlessly:
try {
…
place your library code here
…
} catch (e) {
document.write(‘invoke original library from here’);
}
If your JavaScript code works without errors, your visitor will load one large piece of code. If there are problem blocks, they will be loaded from external libraries. In this case consider rewriting these blocks so that they can be used with the rest of the code without errors.
Popularity: 100% [?]