How to add javascript files according to the viewport / device?

3

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

    
asked by anonymous 27.06.2014 / 22:36

2 answers

4

The simplest way is to read the string User Agent content of the browser, a test to verify that it contains the mobile device indication and to 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...
}

JSFiddle Example

Note: There is no bulletproof method to resolve this issue. For the solution I indicated, the UA string can be manipulated leading to an incorrect detection. Of course I do not see this happening with the common users.

Other common techniques include screen resolution detection and touch support, but these days the new notebooks are already touch-enabled and many of the tablets support high resolutions, / p>     

28.06.2014 / 20:41
2

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

Server-side

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

Client-side

If your pages are statically served (ie plain 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 it is not, dynamically add the skrollr.js script.

As , exactly, you will detect if the mobile browser is your choice; you can use ready-made libraries, detect keywords in userAgent , or use services like link .

I'd like to remind you that detection by size is not always a good idea; tablets and some laptops have high resolution E touchscreen interactivity, which can thwart your plans. Still, I have mentioned only methods that work crossbrowser; as you have already 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 have helped!

    
27.06.2014 / 23:03