Introduction to Javascript and CSS Optimization (Free Preview)
Though images often are the largest assets on a page, Javascript and CSS assets are often the culprits of a slow loading web page. There are several different reasons why this could be, including inefficient code, having a large number of assets on a page, and little or no caching.
We’ll primarily focus on the latter two cases– code optimization is an extremely complex topic and is largely dependent on the website or application in question, though we will address concepts such as asynchronous asset loading.
Resource Bundling
Javascript and CSS files traditionally contain small to medium-sized blocks of code for one particular task. For example, a website traditionally might include a Javascript library or two, the website’s Javascript, and one or more third-party scripts. However, a large number of these scripts can be condensed into a single bundle which reduces the number of network requests required to load the page.
Resource Caching
Another source of latency in a website is often low (or zero) cache time for static assets. With improper cache settings, a web browser will make unnecessary requests to fetch content it should already have in its cache.
Code Loading
There are many ways to load Javascript or CSS into a web page: from simple HTML tags, to dynamic script inject, to asynchronous loading. How you should load your assets largely depends on what the purpose of the asset is, as well as where and when you wish to have the asset loaded.