Avoid unnecessary redirects on mobile sites
Avoiding unnecessary redirects is a general performance best practice but in some cases it can be easy for unwanted redirects to sneak into your application. The performance penalty rendered by unnecessary redirects is of particular importance for mobile users who may be dealing with high-latency, low-bandwidth connections.
Here’s one scenario to watch out for when developing mobile and other device-specific sites.
One redirect
If you’re redirecting a user based on the user’s device you want this redirect to happen only once. So if a user visits www.yourdomain.com and gets redirected to mobile.yourdomain.com, all links from that point on should be relative to the mobile subdomain. If you don’t do this, if your mobile site links back to the www subdomain, you tack on the wait time for the www->mobile redirect to each request. This is dumb.
You’ve probably configured your application or CMS or whatever to output relative URLs, so in most cases you should be OK (but you should check if you’re not sure.) But if your site uses a CMS where users routinely link to other pages—for instance a news site where editors link to other articles—it’s likely that these links contain absolute URLs referring to the desktop site.
That is, a link within an article that references another article may point to http://www.mydomain.com/article-2.html, as opposed to /article-2.html. Following this link from the mobile site results in another redirect. I’ve seen this on a number of mobile sites. Take a look at m.bleacherreport.com or mobile.theverge.com for live examples.
How to fix
It’s an easy thing to fix. One option is to have your CMS filter out same-domain absolute URLs before writing to the database. This is a good solution but requires that you have URL path parity between your desktop and mobile sites.
Another option is to add JavaScript to the mobile site to rewrite the links. Something like this:
// Rewrite article links to relative URLS $('#article-body a').each(function(index, elem) { var oldhref = elem.href, newhref = oldhref.replace('http://www.yourdomain.com', ''); $(elem).attr('href', newhref); });
This requires the same sort of path parity but may be easier to implement.
That’s it
So the takeaway is to avoid cross-domain links that always redirect back to the originating domain. This can happen under various circumstances but a common one concerns mobile sites displaying content with hard-coded references to the desktop site. The solution is to ensure that all links are generated with relative URLs.
Of course you can avoid the problem entirely by not having separate device-specific sites, but that’s another matter!
Discussion