Search code examples
javascriptcssheaderpage-load-time

Javascript and css in header vs including separate document?


Im just curious if there is any advantage to using (a minified version of) javascript and css in the header with the script and style tags vs including them from a separate document via link to css and a script to javascript?

Isn't there theoretically added page load time in the second way since there would be extra page requests?

so this:

<head>

    <script>
        //Javascript
    </script>
    <style>
        //Css
    </style>

</head>

<body>
    //Content Here
</body>

</html>

Vs This:

<head>

    <script src='http://someJavascript.com/link/to/file.js' type='text/javascript'></script>
    <link href='http://someCSS.com/link/to/file.css' rel='stylesheet'>

</head>

<body>
    //Content Here
</body>

</html>

Solution

  • The advantage is mostly modularity. If you use the same JS or CSS in multiple files, it's best to keep them in one place. That way, if you make a change to them, you don't have to update all the files, you just update it in one place.

    But if the JS or CSS is specific to a particular file, you might as well put them directly in the file rather than force a separate request.