Question

Need to know if which approach to include css or js is better -

<link href="http://www.mysite.com/css/style.css" rel="stylesheet" type="text/css"> 
or 
<link href="./style.css" rel="stylesheet" type="text/css"> 

Someone told me that if I use absolute URL (including http://www.mysite.com) then CSS or JS will be downloaded from the server on every page load.

Please help me to understand this.

Was it helpful?

Solution 3

The short answer is: It doesn't matter. Use whichever style you prefer, just try to be consistent.

The long answer is:

People have been asking this kind of question since CSS became a thing. There are all kinds of answers out there that will argue one way or the other, citing performance implications or maintainability.

None of that matters because:

  • Browsers are so efficient that any performance difference is completely moot.
  • Worrying about optimizing your inclusion paths is a distraction, and you're better off just writing code.

OTHER TIPS

You should use relative link because like that your code doesn't relie on your domain. For exemple, if you are changing your domain your don't have to change your code.

What your friend told you is false, the browser download your CSS and js from your server anyway, but it put it in cache for latter uses. So it is not downloaded on every pages.

Absolute URLs provide the full path of the resource. This is usually the case if the resource is from an external domain or some other place. However, providing a fixed location to a resource will cause breakage, especially if you move things around, like say deploy your files on a production server.

For example, you work on localhost on development, and deploy to example.com. You have an index.html that loads a stylesheet named styles.css. Your absolute URL would look like this:

<link href="http://localhost/styles.css" type="text/css" />

But this only works on your local server. But when you deploy, your page will be looking for localhost - but you are in the production server already. It will break.

Relative URLs provide the path of a resource relative to the page that loaded it. It gives you more flexibility, especially when moving the page around.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top