简体   繁体   中英

best method of detecting mobile browsers with javascript/jquery?

For a site I'm working on I'm implementing image preloading with javascript however i most certainly do not want to call my preload_images() function if someone is on slow bandwidth.

For my market the only people with slow bandwidth are those using mobile internet on a smartphone.

What's the best approach for detecting these users so i can avoid image preloading for them?


option 1 : detect browser width

if($(window).width() > 960){ preload... }

option 2: detect user-agent with a list of browser to preload for

if($.browser in array safelist){ preload... }

are there any better options?

I find that I dislike sites that decide which version of the site I should access on a particular device or environment. It's great to make an initial decision based on whatever criteria you settle on, but for goodness sake, give me a link I can click so I can choose the "Higher Bandwidth Site" or vice versa and save it to a cookie. Then I can override any error the automated script makes with my own judgement.

Maybe using the CSS @media directive, along with hidden objects?

.imagesToPreload {display:none;}
@media screen {
    #imageToPreload1 {background-image:url('blah.img');}
}
@media handheld {
    #imageToPreload1 {background-image:none;}
}

Then in Javascript, you can fetch all objects in "imagesToPreload" class, read the backgroundImage property and preload it if its not none.

Admittedly, this is off the top of my head, I didn't test this idea. As usual, there must be something I am not thinking about...

I think edeverett's point about mobile not necessarily being slow (and similarly desktop not necessarily being fast) is a good one.

Remember not to remove choice for your visitors - ie most decent mobile browsers have an option not to load images (or specifically not to load large ones) and also avail of proxy services that compress images before downloading - some mobile visitors may want the full preloaded experience on your site.

Another solution might be something like: if($(window).width() < 320){ preload_smaller_images(); } if($(window).width() < 320){ preload_smaller_images(); } There's less reason than there used to for the mobile browsing experience to be more limited than that of the desktop.

R. Hill's CSS suggestion is not the worst though (if it can be done in CSS, it should imo), it can also be done per-screen-size: @media handheld, screen and (max-width: 320px){ /* */ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM