zbauman
zbauman

Reputation: 225

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>

Upvotes: 0

Views: 660

Answers (3)

John - Not A Number
John - Not A Number

Reputation: 659

Having the JavaScript and CSS in separate files allows browsers and proxies to cache them - so if the main section of the page is dynamically generated, only the changing content will get re-downloaded on a reload.

Upvotes: 0

Barmar
Barmar

Reputation: 780879

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.

Upvotes: 1

csander
csander

Reputation: 1380

I would generally do the scripting or styling inline, although it is useful to load it remotely if you want something for multiple different HTML files (e.g. the same stylesheet for all the pages on a website). Load times increase a bit, but unless you are expecting to get thousands of page loads, it's pretty minimal. Your "header" tags should also be "head" tags.

Upvotes: 0

Related Questions