Sunday, June 22, 2014

HTML - Stylesheets and Scripts placement

Place stylesheets inside <head> , if possible. Combine & minimize the files to reduce request numbers. Ideally, there should be only one or two stylesheets.

Example:
<head>
    ...
    <link rel="stylesheet" type="text/css" href="..." media="screen" />
    <link rel="stylesheet" type="text/css" href="..." media="print" />
    ...

</head>

Reasons: 

Avoid the “content flickering”, if the stylesheets are loaded after the DOM is ready, the content will be repainted, causing the flickering.

Read more:
http://en.wikipedia.org/wiki/Flash_of_unstyled_content


Place scripts right before </body>, if possible. Avoid placing JavaScript codes in HTML files, keep codes clean separated. Combine & minify the files too, same as stylesheets.

Example:
<body>
    ...
    <script src="..."></script>
    <script src="..."></script>
</body>

Reasons: 

 Prevent the scripts from stopping the content to parse. So the page won’t choke on the big JavaScript files.

Read more:

For .NET projects, http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

Ideal outcome

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]>         <html class="lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]>         <html class="lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="" lang=""> <!--<![endif]-->
<head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    ...
    <link rel="stylesheet" type="text/css" href="...">
</head>
<body>
    ...
    <script src="..."></script>
</body>
</html>

No comments:

Post a Comment