Download javascript file and css file depending on user agent

As in the title.

I have two files: one is a javascript file and one is a css file. And if the user agent is an iPad , I want to download these files, but only when the user agent is an iPad . Thus, below the two lines are loaded only when the user agent is an iPad. how can i achieve this

<link rel="stylesheet" href="/c/dropkick.css" type="text/css"/> <script src="/s/jquery.dropkick-1.0.0.js" type="text/javascript"></script> 
+6
source share
2 answers
 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 the User-Agent for iPad header is.

Literature:

+10
source

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

This answer here, on SO, offers you an IP address, just looking for the string "ipad" in the navigator.userAgent field. Of course, the user agent field can be faked.

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 it's out of the cuff, unchecked.

(Note that there is no reason to put the type in a link or script ; in the case of link type comes from the type of the content of the response. In the case of script , JavaScript is used by default.)

+2
source

All Articles