Cascading Style Sheets (CSS) and JavaScript (JS) Primer: how to include in your markup

All assets (JS, CSS, and images) can be cached client-side separate of the markup so far-future expiry headers and storing as much code as possible in external files (as opposed to served in the HTML markup) allows for the fastest possible page loads.

Include CSS (should always be loaded as early as possible and before the elements it styles are added to the DOM).

...
<head>
    ...
    <link rel="stylesheet" type="text/css" href="http://path/to/file.css"/>
    <style type="text/css">/*<![CDATA[*/
        /* CDATA tags are needed to ensure well-formed XML+HTML */
        /* page-specific CSS _can_ be added, but should be avoided. */
        html,
        body { margin: 0; padding: 0; }
    /*]]>*/</style>
</head>
...

Include JS (should always be loaded as late as possible):

...
<head>
    ...
    <script type="text/javascript" href="http://path/to/library/file.js"/>
</head>
<body ...>
...
    <script type="text/javascript">/*<![CDATA[*/
        /* CDATA tags are needed to ensure well-formed XML+HTML */
        // page-specific JavaScript here (at the bottom of the BODY tag)
        if(true && 1 > 0) {
            alert("DOM almost ready.");
        }
    /*]]>*/</script>
</body>
</html>

Include JS in XHTML (CDATA tags needed if any characters need entitizing):

...
<head>
    ...
    <script type="text/javascript" href="http://path/to/library/file.js"/>
</head>
<body ...>
...
    <script type="text/javascript">/*<![CDATA[*/
        /* CDATA tags are needed to ensure well-formed XML+HTML */
        // page-specific JavaScript here (at the bottom of the BODY tag)
        if(true && 1 > 0) {
            alert("DOM almost ready.");
        }
    /*]]>*/</script>
</body>
</html>


About this entry