Search code examples
htmlhyperlinkhref

Root-linking (/) VS absolute-linking (eg. http://www.)


I am currently using root-linking on my sites eg. <a href="/">Home</a> and <a href="/contact">Contact</a>. I like this since it makes the code a bit cleaner.

Though I wonder if there is any disadvantages using this method eg. if it some how slows down page speed or is bad for SEO?

Edit:

Also I wonder about images:

Would for example "http://www.domain.com/img/image1.jpg" load any quicker than "/img/image1.jpg"? If yes, is it more than 50 milliseconds?

I know that absolute linking is hard to maintain for eg. localhost or if you want to change to "https://". But I still wonder about the speed...


Solution

  • It does not make a difference from a technical point of view. The browser needs to construct an absolute URL before making any HTTP requests. Section 2.5 of the HTML5 specification contains precise instructions how to resolve URLs, e.g. for the href attribute. The fourth step is relevant:

    If the algorithm was invoked with an absolute URL to use as the base URL, let base be that absolute URL.

    Otherwise, let base be the element's base URL.

    The "element's base URL" is usually the same as the base URL of the document, unless you explicitely change it.

    This is the only point at which the notation of the URL makes a difference. The parameter base and the URL will be passed to a parser, which then constructs an absolute URL from these values. If the document URL is https://example.com/foo/bar.html, then resolving /stackoverflow and https://example.com/stackoverflow will yield the same URL (https://example.com/stackoverflow).


    After resolving the URL, the browser will usually make an HTTP request to the server. This will most likely not include a DNS request as the DNS cache most probably contains an entry for that host.
    The HTTP request itself will also look the same (hostname and path are transmitted separately).


    Talking about performance, there is literally no difference. (Unless you consider those few nanoseconds required to find the base URL in the DOM.)

    It is just a matter of notation and it is usually simpler to write relative URLs (either relative to the document or relative to the root directory), however if you are making anything more than a static website, you should consider generating absolute URLs on the server. For example, a user might decide not to use your application in the root directory, but in a subdirectory, so all root-relative URLs would break.


    The same applies to SEO, search engines and crawlers construct absolute URLs exactly as browsers do.