Arieh.co.il

quick post - Adaptive image sizes for mobile devices

Adaptive images

This is a very quick post that I felt like I had to write.

While doing my daily reading, I came around this nice article about adaptive image sizes. I won't go into the issue itself since the article is quite good on that, but it involves trying to send different images to different scren sizes.

What I don't like about his solution is that it involves using a php file to choose the right image. The reason it seems wierd to me is that there is a special element in HTML that is tailored for this issue - the BASE element.

The base Element

The base element specifies a document-wide base URL for the purposes of resolving relative URLs, and a document-wide default browsing context name for the purposes of following hyperlinks.

W3C Documentation

Basically, the base element allows you to specify what path to use for relative URLs in your site. Are you with me now?

The solution

So - I did some fast trial and error, and it works. Kind of - you must use document.write(hiding my face with shame)

Since this has to come into the redering phase of the page - you must make the browser think it's part of the document. Here's the code:

if (window.innerWidth < 400){
    document.write('');
}   

And for a demo -

And that's it - any resource trying to use relative path will be directed to that url.

Now - I can already here you saying but - what about all other resources on our page?. Well - I guess you're right - it's a tradeoff - but one that's much easier to fix IMO. You can either use non-relative URLs, or you can create links to the proper folders (assuming you have a scripts, css, images folders, simply link the 1st two).

JavaScript Reference, JavaScript Guide, JavaScript API, JS API, JS Guide, JS Reference, Learn JS, JS Documentation