Chapter 10. Rule 8: Make JavaScript and CSS External
Many of the performance rules in this book deal with how external
components are managed, such as serving them via a CDN (Rule 2), making
sure they have a far future Expires
header (Rule 3), and compressing their contents (Rule 4). However, before
these considerations arise, you should ask a more basic question: should
JavaScript and CSS be contained in external files or inlined in the page
itself? As we'll see, using external files is generally better.
Inline vs. External
Let's first start with the tradeoffs in placing JavaScript and CSS inline versus using external files.
In Raw Terms, Inline Is Faster
I have generated two examples that demonstrate how inlining JavaScript and CSS results in faster response times than making them external files.
- Inlined JS and CSS
- External JS and CSS
The inline example involves one HTML document that is 87K, with all of the JavaScript and CSS in the page itself. The external example contains an HTML document (7K), one stylesheet (59K), and three scripts (1K, 11K, and 9K) for a total of 87K. Although the total amount of data downloaded is the same, the inline example is 30–50% faster than the external example. This is primarily because the external example suffers from the overhead of multiple HTTP requests (see Chapter 3 about the importance of minimizing HTTP requests). The external example even benefits from the stylesheet ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access