In my opinion, i Prefer to Detect the hosting device Screen Size, Width mainly. for two reasons:
You cannot identify all the mobile devices in the market (especially Chinese).
Some Tablets behave like Desktops, and others like Phones.
So the only thing that can help you identify the manner to render your pages is checking your device Screen Width, which is not just more accurate but also much easier.
Here is a code to implement what Yep commented. I personally prefer that method too, since you can’t guess all the user agents out there so you can simply rely on width and height (width mainly):