How to add javascript files according to viewport/device?

Asked

Viewed 97 times

3

I’m using the script skrollr.js on a website and when opening on mobile phones the scroll bar is not working (it is as if the touch of the phone was blocked). I wanted to know how to disable scripts when the user accesses mobile phones, since I don’t want to use skrollr in this situation. It would be like a media query for javascript.

2 answers

4


The simplest way is to read the contents of string User Agent of the browser, make a test to check whether it contains the indication of mobile device and act accordingly:

Javascript

if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    // utilizador em dispositivo móvel, agir em conformidade.
}
else {

    // não é dispositivo móvel

    // adicionar a tag de script ao DOM
    var script  = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "caminho/para/skrollr.js";
    document.body.appendChild(script);

    // iniciar o skrollr aqui...
}

Example in Jsfiddle


Note: There is no bullet-proof method to resolve this issue. For the solution I indicated, the AU string can be manipulated leading to incorrect detection. Of course I don’t see that happening to the average user.


Other common techniques are screen resolution detection and touch support, but nowadays the new laptops already come with touch support and many of the tablets support high resolutions, which ends up making these methods impossible.

2

There are two ways: server-side or client-side.

Server-side

It depends heavily on the language. Some already have well-established libraries for client detection from the HTTP request header. If your pages are generated dynamically, a good approach would be to provide a version without the script statement.

Client-side

If your pages are statically served (i.e., pure HTML), the best option is to serve them without calling the script. You can then detect through a small custom script if the browser is mobile; if not, dynamically add skrollr.js script.

Like, exactly, you will detect if the browser is mobile gets your choice; you can utilize ready libraries, detect keywords in the userAgent or use services such as http://detectmobilebrowsers.com/.

I take this opportunity to remind you that size detection is not always a good idea; tablets and some laptops have high resolution And touchscreen interactivity, which can frustrate your plans. Still, I only mentioned methods that work crossbrowser; as you yourself mentioned, media query and some other new technologies can be used as well, but at the cost of not working in legacy browsers.

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.