开发者

Basic JS question: how to do 'else, load javascript'

I have a bit of Javascript I want to the iPad/iPhone to ignore, but for other browsers to read. The JS is:

<script src="scripts/jquery.anchor.js" type="text/javascript"></script>

I've found some code on this site to target a particular device, as follows:

<script>
var userAgent = navigator.userAgent;

if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) {
   // iPad or iPhone
}
else {
   // Anything else
}
</script>

I'm a JavaScript newbie 开发者_开发知识库and wouldn't know the syntax to place the script after the // Anything else comment... any help appreciated. Thanks!


Don't test for the browser, test for the functionalities it offers.

If there's a function which is not supported by all the browsers, don't test for which browsers don't support it because what if it supports it in the future?

Do something like this instead:

if (nonStandardFunction) {
    nonStandardFunction();
}

That way, any browser which supports it will execute it, and you don't care which ones do or don't.

You can also add the functionality yourself:

window.nonStandardFunction = window.nonStandardFunction || function () {      
    // your implementation
};

If on the other hand you specifically don't want an i<Device> to access it, test for the user agent.

Here's an example of what you can do:

var addJS = function (file) {
  var head = document.getElementsByTagName('head')[0],
      script= document.createElement("script");

  script.type = "text/javascript"; // redundant
  script.src = file;
  head.appendChild(script);
}, userAgent = navigator.userAgent,
   isNotiDevice = !(userAgent.match(/iPad/i) || userAgent.match(/iPhone/i));

if (isNotiDevice) {
    addJS('scripts/jquery.anchor.js');  
}


Not sure if this helps, but you could possibly use

   <script id="someID" type="text/javascript"></script>

and then

   document.getElementById('someID').src= 'script.js';

And just tailor it within your if statement for a specific browser.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜