Load a javascript file and css file depending on user agent

≡放荡痞女 提交于 2019-11-28 13:40:31
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:

T.J. Crowder

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.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!