简体   繁体   中英

Media Query approach to Javascript

I am looking at implementing/calling JS based on the device-type like how we use CSS Media Queries.

<link rel="stylesheet" type="text/css" href="desktop.css" media="all" />
<link rel="stylesheet" type="text/css" href="ipad.css" media="only screen and (device-width:768px)" />

Similarly can we define some JS and call them based on the device (desktop/mobile)

I know one obvious approach is just to use an if statement to separate the 2 like

if (navigation.userAgent.match(/iPad/) != null)

But what I am looking at is only the right JS should be loaded/called in the device eg only desktop.js should be called for desktop and only iPad.js for iPad (similar to how css media queries render)

Please suggest.

This should be refined to:

// put this in the end of the page to add JS to body (perfomance optimisation on loading behaviour

var body = document.getElementsByTagName('body')[0];
var script = document.createElement('script');
script.type = 'text/javascript'; // you can omit this when using HTML5 Doctype
if (navigation.userAgent.match(/iPad/) != null) {
script.src = 'ipad.js';
} else {
    script.src = 'desktop.js';
}
body.appendChild(script);

You could dynamically put the script tag for the correct file into the page like this:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
if (navigation.userAgent.match(/iPad/) != null) {
    script.src = 'ipad.js';
} else {
    script.src = 'desktop.js';
}
head.appendChild(script);

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