Optimize the Loading Order of CSS and JavaScript


Part One Chapter 16

CSS JavaScript

Calls to external CSS files and inline CSS codes should be placed before calls to external JavaScript files and inline JavaScript codes. If you do this your mobile web pages will load faster.

This is how a typical browser responses to CSS and JavaScript when loading a web page:

  • When a web browser is loading your mobile web page, it first receives the HTML, and then it starts getting all the resource files (i.e. CSS, JavaScript, images, etc) of the page.
  • When the web browser starts downloading JavaScript, it stops loading anything else until the JavaScript is completely loaded. This is the reason that you should not place JavaScript before CSS.

The Wrong Way

The HTML code below shows all the external JavaScript files are placed before all the external CSS files and inline CSS codes. This does not achieve the optimal order for page load speed.

<head>
<script src="http://res.example.com/script.js"></script>
<script src="http://m.example-2.com/script2.js"></script>
<link rel="stylesheet" href="http://res.example.com/style.css" />
<link rel="stylesheet" href="http://m.example-2.com/style2.css" />
<style>
#section1 {
  background-color: red;
  color: white;
  font-family: "Courier New";
  text-align: left;
  padding: 10px;
}
#section2 {
  color: grey;
  font-size: 0.8em;
  font-style: italic;
}
</style>
</head>

The Right Way

The HTML code below demonstrates all the external CSS files and inline CSS codes are placed before all the external JavaScript files. This is the correct way and optimal order for page load speed.

<head>
<link rel="stylesheet" href="http://res.example.com/style.css" />
<link rel="stylesheet" href="http://m.example-2.com/style2.css" />
<style>
#section1 {
  background-color: red;
  color: white;
  font-family: "Courier New";
  text-align: left;
  padding: 10px;
}
#section2 {
  color: grey;
  font-size: 0.8em;
  font-style: italic;
}
</style>
<script src="http://res.example.com/script.js"></script>
<script src="http://m.example-2.com/script2.js"></script>
</head>


Gordon Choi's Mobile Website Book has been available since November 2016.







Content on Gordon Choi's Mobile Website Book is licensed under the CC Attribution-Noncommercial 4.0 International license.

Gordon Choi's Mobile Website Book

Gordon Choi’s Other Books:
The China Mobile SEO Book
Analytics Book