Using Absolute Versus Relative Paths for Images

后端 未结 3 1520
感情败类
感情败类 2021-01-05 12:59

A coworker just asked me if there were any reason why referring to images with a relative path would impede site speed.

While for cleanliness it\'s a good idea to h

相关标签:
3条回答
  • 2021-01-05 13:30

    Using absolute paths forces the web server to establish a connection, send and receive the HTTP requests. If using relative, the connection is already established, so it doesn't have to go through that logic (hence increasing page load speed). You probably won't see an amazing difference, but every bit saved is a good thing, right?


    Edit: After doing a quick test, the difference is extremely negligible, and doesn't seem to produce that great of a case for my answer. I created a test page with the same image twice, one with relative and one with absolute path: http://damonbauer.me/test/index.html.

    Test One: Image w/ Absolute path in HTML code first: (click for larger version) http://damonbauer.me/test/images/results1.jpg

    The absolute path image took 869ms to load, while the relative path image, listed second in the HTML code, loaded in 635ms.

    Test Two: Image w/ Relative path in HTML code first: (click for larger version) http://damonbauer.me/test/images/results1.jpg

    The absolute path image took 303ms to load, while the relative path image, listed first in the HTML code, loaded in 315ms.

    My opinion? It's faster to load using relative. Even when listed after the absolute path image, it took only 12ms longer for the relative image to load. When the absolute path image was loaded second, it took it 234ms longer to load. In both cases, they are close, and it looks to me like it matters more about what loads first. Either way, I would go with relative, if only for portability's sake.

    0 讨论(0)
  • 2021-01-05 13:33

    A remote absolute path will go thru DNS but it frees up your web server to serve pages while another server gets the work of serving images. That lightens the network load on the page server and speeds things up.

    A local absolute path will be the same as local relative in that after the first page it, it will be cached by the web server and it's not going to matter after that.

    0 讨论(0)
  • 2021-01-05 13:40

    nah, there isn't any noticeable difference, and both have their uses. There is no DNS lookup client-side, it's the browser (or maybe the web server?) that changes the url to what it should be. Use them as what you need to, relative paths are more portable (no need to do anything to make them work in your development or live server), while absolute paths take you to specific location (regardless in what server you are).
    In my case, I use relative paths unless I want a specific address to be used. Also, when you're switching from non-secure to secure, you'd want to specify https so full path (or do an extra redirect somewhere else)

    0 讨论(0)
提交回复
热议问题