6

Just like in the title.

I got two files: one is javascript file and one is css file. And if user-agent is an iPad I want to load those files - but only when user-agent is iPad. So below two lines are only loaded when user-agent is an iPad. how can i achieve that

<link rel="stylesheet" href="/c/dropkick.css" type="text/css"/>
<script src="/s/jquery.dropkick-1.0.0.js" type="text/javascript"></script>
born2fr4g
  • 1,290
  • 4
  • 27
  • 38

2 Answers2

11
if (navigator.userAgent.match(/iPad/i) != null){ // may need changing?
  var js = document.createElement('script');
  js.type = "text/javascript";
  js.src = "/s/jquery.dropkick-1.0.0.js";

  var css = document.createElement('link');
  css.type = "text/css";
  css.rel = "stylesheet";
  css.href = "/c/dropkick.css";

  var h = document.getElementsByTagName('head')[0];
  h.appendChild(js);
  h.appendChild(css);
}

Or whatever would be in the User-Agent header for an iPad.

References:

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
2

You can use document.createElement to create link and script elements, and then append them to the document (for instance, append them to document.getElementsByTagName('head')[0] or similar).

This answer here on SO suggests that you can dtect an iPad by just looking for the string "ipad" in the navigator.userAgent field. Of course, the user agent field can be spoofed.

So for example:

<script>
(function() {
    var elm, head;

    if (navigator.userAgent.indexOf("ipad") !== -1) {
        head = document.getElementsByTagName('head')[0] || document.body || document.documentElement;

        elm = document.createElement('link');
        elm.rel = "stylesheet";
        elm.href = "/c/dropkick.css";
        head.appendChild(elm);

        elm = document.createElement('script');
        elm.src = "/s/jquery.dropkick-1.0.0.js";
        head.appendChild(elm);
    }
})();
</script>

...but that's off-the-cuff, untested.

(Note that there's no reason to put the type on either link or script; in the case of link, the type comes from the content-type of the response. In the case of script, the default is JavaScript.)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Though I agree you don't _need_ to specify type, I get sketching from the old days of `foo.png` containing `Content-Type: text/javascript` in the header. I guess I feel like explicit is safer than implicit in a lot of cases. – Brad Christie Dec 10 '12 at 14:21
  • @BradChristie: Right, but `type` on `link` when there's a `rel="stylesheet"` isn't explicit, it's a no-op, see [here](http://www.w3.org/TR/html5/the-link-element.html#attr-link-type) and [here](http://www.w3.org/TR/html5/links.html#link-type-stylesheet). Similarly on `script`, the default is and **always** has been JavaScript, even on IE5 when Microsoft thought they could compete using VBScript. :-) – T.J. Crowder Dec 10 '12 at 14:27