开发者

Media Query approach to Javascript

开发者 https://www.devze.com 2023-04-11 22:29 出处:网络
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\" />

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 e.g. 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消