Include different JavaScript file depending on browser? - javascript

I want to include a JavaScript file only if the browser is not IE. Is there any way to do this?

Update 2022:
Some options for you:
Have your server look at the User-Agent header and send different HTML to Internet Explorer vs. other browsers.
Pros:
No client-side solution required.
Cons:
Relying on User-Agent strings is notoriously error-prone, and they can be spoofed or entirely absent.
Sniff navigator.userAgent and either output a script tag or not depending on what you find.
Pros:
No server-side requirement.
Cons:
Same as #1: Relying on User-Agent strings is notoriously error-prone, and they can be spoofed or entirely absent.
Some people have an issue with outputting script tags from code, particularly via document.write, but depending on your use case document.write may be unavoidable (e.g., do you need the script there before some other script, etc.).
Sniff for something in the JavaScript runtime that only Internet Explorer has, and output a script tag or not based on what you find.
Pros:
No server-side requirement.
No user-agent sniffing.
Cons:
The issue some people have with dynamically adding script tags.
I'd probably look at #3. For instance, any even vaguely modern browser has the Symbol function. Internet Explorer does not. So:
if (typeof Symbol !== "undefined") {
document.write("<script src='./your-non-ie-script.js'><\/script>");
// Or if you prefer
let script = document.createElement("script");
script.src = "./your-non-ie-script.js";
document.activeElement.parentNode.appendChild(script);
}
Symbol is just one example, IE lacks Reflect, Proxy, and a few others from ES2015 that everything else has now...
(Not sure why I didn't mention this in 2013!)
Update 2013: IE10+ don't support conditional comments anymore.
You can do it with IE's conditional comments, like so:
<![if !IE]>
<script src="your-non-IE-script.js" type="text/javascript"></script>
<![endif]>
Note that the above is processed by non-IE browsers because the conditional is not an HTML comment, but a processing instruction, so the bit in the middle is processed by non-IE browsers. IE sees the conditional and skips over the content because it understands the conditional means "Not you, move along."
If you want to do something only for IE, you use a form that's similar, but uses HTML comments instead (with the --) because that's the only way you can rely on other browsers ignoring the contents. IE knows to pay attention to them, even though they're comments. More on the link above.
Note that there's a page load speed implication on IE (not the other browsers) when you use conditional comments (they temporarily block download of other resources), more here: http://www.phpied.com/conditional-comments-block-downloads/

You can use an IE conditional comment.
To get something that will show up in browsers other than IE, but not in IE, and which will still validate, you can use:
<!--[if !IE]>-->
<script src="..."></script>
<!--<![endif]-->

First, a note: This isn't really a good practice. If possible, you should strive to design your website in a browser-agnostic way, so that it works consistently across all browsers without the need to maintain hacks and tricks for browser-specific problems.
But if you really want to do this, it's easiest to include a file only if the browser is IE:
<!--[if lt IE 7]>
<script type="text/javascript" src="global.js"></script>
<![endif]-->
(Includes the file only if the browser is IE6 or less.)
However, if you really want to do it the other way around, here are some of your options:
Use server-side browser sniffing to process the browser before the page is drawn. That is, use a server-side language (Java, PHP, whatever) to determine what the browser is (usually through the user agent string) and then conditionally include your JS files that way. (For example, you can use PHP's get_browser function.)
Use client-side browser sniffing to call another JS file if the browser is not IE. You can determine the browser using JavaScript itself, and then insert another JS file into the page if the browser is anything but IE. (For example, you can use jQuery's browser function.)
T.J.'s answer provides a way of doing it with I.E.'s conditional comments as well.

It's lesser known than conditional comments, but I thought I'd mention that you can also use an IE feature called conditional compilation - see http://msdn.microsoft.com/en-us/library/7kx09ct1%28VS.80%29.aspx
This example comes from their docs:
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
document.write("JScript Version 5.0 or better.<BR>");
#else #*/
document.write("You need a more recent script engine.<BR>");
/*#end #*/

You can do that totally different way [inserting something ONLY if IE] using Conditional Comments, maybe that would help you.
http://en.wikipedia.org/wiki/Conditional_comment

Yes, conditional scripts for IE is your answer:
<!--[if lt IE 7 ]>
<script src="/js/my_ie_script.js"></script>
<![endif]-->

How about turning it around? If this is a possibility you can use IE's conditional comments: http://www.quirksmode.org/css/condcom.html
Otherwise you could sniff user-agents but this is considered 'bad practice'.

Here's an solution working in 2022
<html>
<head>
<script>
// Test if running in Internet Explorer or not
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1 || myNav.indexOf('trident') != -1) ? true : false;
}
if (isIE()) {
var script = document.createElement('script');
script.src = "https://unpkg.com/core-js-bundle#3.6.5/minified.js";
document.head.appendChild(script);
}
</script>
</head>
<body>
</body>
</html>

Related

What difference does having attributes in the <script> tag make compared with no attributes? [duplicate]

I read somewhere that you no longer need things like type="text/javascript" and the weird CDATA and <!-- things in your script tags. So, instead of:
<script type="text/javascript">
//<![CDATA[
<!--
//your script here
-->
//]]>
</script>
You would just do:
<script>
//your script here
</script>
I can't remember where I read this though. It was from a Google or Yahoo engineer I think, and they specifically mentioned which browsers required these archaic constructs and why. Anyone know what blog post/article this was talked about, or have a good resource talking about this?
See Crockford's write-up on the <script> tag, most notably:
Do not use the <!-- //--> hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic. It has not been necessary for many years. <!-- //--> is supposed to signal an HTML comment. Comments should be ignored, not compiled and executed. Also, HTML comments are not to include --, so a script that decrements has an HTML error.
...
type="text/javascript"
This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.
It's a Crockford recommendation. I know I've seen it echoed elsewhere (ppk maybe?). The HTML5 spec does not require it.
Oddly, it's become somewhat au courant to use the "type" attribute to mark <script> blocks that you don't want to be evaluated:
<script type='text/html-template'>
<div> this is a template </div>
</script>
By giving a weird non-JavaScript type, you get a way to stuff raw text into the page for use by other JavaScript code (which is presumably in script block that can be evaluated).
HTML5 doesn't need the type="text/javascript" (it's the default).
CDATA is only neeed for XHTML pages, if the script has any HTML characters (like '<' and '>') in it.
<!-- should only be needed for OLD browsers.
The type attribute identifies the scripting language of code embedded within a script element or referenced via the element’s src attribute. This is specified as a MIME type; examples of supported MIME types include text/javascript, text/ecmascript, application/javascript, and application/ecmascript.
According to HTML 4.01 Specification
The type attribute specifies the scripting language of the element's
contents and overrides the default scripting language. The scripting
language is specified as a content type (e.g., "text/javascript").
Authors must supply a value for this attribute. There is no default
value for this attribute.
But in HTML5 text/javascript is the default type, so you can omit
The type attribute gives the language of the script or format of the
data. If the attribute is present, its value must be a valid MIME
type. The charset parameter must not be specified. The default, which
is used if the attribute is absent, is "text/javascript".
Well, I am tempted to say that nobody is using text/javascript any more, and that even minification tools would probably remove it...
Indeed, Facebook SDK documentation specifies just <script>.
However,
Google SDK documentation still has text/javascript.
Amazon SDK documentation still has text/javascript.
Linkedin API documentation still has text/javascript.
Instagram is still using text/javascript.
you may be thinking of this article here with the dependency being that scripts default to text/javascript in HTML5 automatically, while non-HTML5 browsers still expect that you define the type specifically spec-wise even though they will almost always guess text/javascript anyways.
👉🏻 The HTML5 specification urges authors to omit the attribute rather than provide a redundant MIME type. MDN
The MIME Sniffing Standard lets JavaScript be served using any MIME type (Multipurpose Internet Mail Extensions) that matches the following:
<script type="application/javascript"></script>
<script type="application/ecmascript"></script>
<script type="text/javascript"></script>
<script type="text/ecmascript"></script>
it's up to the browser to interpret the script block correctly based on the headers, i believe, and not the type attribute. So to answer your question, no it is not required for modern browsers (i'm talking IE7+, FF, Webkit). If you are supporting older browsers than that...I feel sorry for you =)
If you're putting a script tag inside SVG you must specify the type attribute. And it should be "text/ecmascript" rather than "text/javascript".
If your script is inline (not linked) you will need to wrap the script body in a CDATA declaration too. The inline script boilerplate for SVG (and other XML variants) is thus
<script type="text/ecmascript">
<![CDATA[
// your javascript code goes here
]]>
</script>
These might be special cases 'in the wild', but they are real enough, and SVG use is growing, so it's incorrect for anyone else to suggest that the type attribute and CDATA are entirely obsolete in modern browsers. The use cases are narrow, yes, but not unheard of.
"Change the environment to its opposite and every piece of wisdom becomes the worst of folly." - Ashby
Well i keep seeing more examples without the text/javascript but for some reason my scripts wont work in FF when i do so. I would recommend keeping the text/javascript declaration. The CDATA tag prevents javascript from being shown as plain text in your website if your browser has javascript turned off. Personally i don't use those tags anymore don't think there's allot of users out there without and if they are out there they might wanna grow some brains :P
type="text/javascript" : Required in HTML 4 and XHTML, but optional in HTML5.
CDATA : Required in XHTML.
<!-- : Used to hide the JavaScript from very old browsers. Eg: Netscape 1 and Internet Explorer 2, neither of which anyone uses any more.

JavaScript / HTML: Disable Block of Code Only in Opera

I want to tell Opera to ignore a block of JavaScript code, but I want all other browsers to recognize that code, something like this:
if NOT Opera:
<script type="text/javascript">
// Code
</script>
Or maybe rather:
<script type="text/javascript">
if NOT Opera:
// Code
</script>
Is there a solution? I would be grateful for your help!
This should do the trick :
<script type="text/javascript">
if(navigator.userAgent.indexOf("Opera") < 0 ) {
// Code
}
</script>
Pretty much all you need is to take a look at the window.navigator.userAgent variable. Within it you'll find a string containing information about the browser you are using. I have no access to a version of safari so I can't really test this out for you -
if (window.navigator.userAgent.match('/safari/i')){
// user is using safari
}
References -
window.navigator.userAgent
string.match
Keep in mind that this is not the best way to do browser detection and will not prevent people from using your site with safari - your JavaScript is viewable and editable by all so if you are thinking of this as a security feature you might want to reconsider it.
I would suggest detecting the users browser on the server side (if you are using PHP then you could use $_SERVER['HTTP_USER_AGENT']) and then have the server return different JavaScript files according to the users browser.

Will non-IE browsers use script inside a tag with type="text/jscript"?

I inherited an ancient codebase that includes pages with <script type="text/jscript"> -- yes, my life really does suck that much. The script appears to do nothing in modern, decent browsers (FF and Chrome, for a start) and I'm wondering if the stated script type is causing it to be ignored. I spent some time trying to figure out what's going on, and I see things like
As explained by JavaScript guru Douglas Crockford in his talk entitled The JavaScript Programming Language on YUI Theater, "[Microsoft] did not want to deal with Sun about the trademark issue, and so they called their implementation JScript. A lot of people think that JScript and JavaScript are different but similar languages. That's not the case. They are just different names for the same language, and the reason the names are different was to get around trademark issues."
on Wikipedia. So Javascript == JScript? But then, I see conflicting information, like this answer which seems to suggest that script that's declared as JScript will only run in IE.
So: can I just change the type tag and everything will work fine? Is there a simple process for conversion? If not, I may just scrap the whole thing and start over.
From HTML 5 chapter 4.3
7) If the user agent does not support the scripting language given by the script block's type for this script element, then the user agent must abort these steps at this point. The script is not executed.
That same chapter also says
If either:
the script element has a type attribute and its value is the empty string, or
the script element has no type attribute but it has a language attribute and that attribute's value is the empty string, or
the script element has neither a type attribute nor a language attribute, then
...let the script block's type for this script element be "text/javascript".
so I would just remove type="text/jscript" save a bit on bandwidth and live happily ever after.
So Javascript == JScript?
JScript is what Microsoft calls JavaScript
But then, I see conflicting information, like this answer which seems to suggest that script that's declared as JScript will only run in IE.
That doesn't conflict. It just means that other browsers don't recognise the mime type.
Browsers will ignore script elements with a type they do not recognise. text/jscript is non-standard and most browsers don't recognise it (Internet Explorer considers it an alias for text/javascript).
can I just change the type tag and everything will work fine?
Probably. The script might depend on other proprietary Microsoft—isms (such as document.all) or other non-standard behaviour (automatic id attribute to JS global conversion or treating CSS lengths that are missing a unit as pixels) though.
The other answer you linked to is completely incorrect. There are no differences between JScript and JavaScript. Changing the script type to "text/javascript" should work (unless the intent of the author was to force it so that only IE ran the script)
the type= requirements have been taken out of html5. I believe the proper xhtml code would be ...
<script type="text/javascript">
<![CDATA[
// content of your Javascript goes here
]]>
</script>
... but browsers did not follow the requirements of xhtml of forcing an error. Most web hosts keep the delivery of xhtml and html docs as MIME-type "text/html", not the "application/xhtml+xml" which should force an error if the xhtml does not validate.
HTML4 uses are variety of types ... http://www.w3.org/TR/html4/interact/scripts.html ... but browsers do not force html4 validation.
vscript, tcl don't have common support - we are talking about Javascript or any of the other names it gets as in becomes a more powerful language.
A bogus "type" attribute will definitely make scripts not work. The browser thinks you don't want it to run the script, basically.
Really, the "type" attribute is not necessary unless you definitely don't want the browser to run a script (which people do when their "scripts" are actually template bodies, or other data like that). You could either change all yours to "text/javascript" or just get rid of the attribute entirely.

browser identification

I want to identify if the broswer is IE then goto if block, other browser to else block in Java script.
I have one code here,
var browserName=navigator.appName;
if(browserName == "Microsoft Internet Explorer"){
IE code
}
else{
Other code
}
but i want to know is there any other way of implementing it?
Rather than do browser sniffing, you should do feature detection. Later versions of IE may support standards compliant stuff that in older versions you needed to work around or use MS-specific stuff.
Microsoft themselves have written up about the best way to do this and provide examples of both bad code (via sniffing) and good code (via detection). Make sure you go down the "good code" route.
I just started using this script to identify browser, version, and OS:
http://www.quirksmode.org/js/detect.html
If you are needing to use different code based on browser support for certain objects or methods, it's usually better to use object or method detection instead of browser detection. I use the browser detection for collecting statistics on my users, not for enabling or disabling features.
Quirksmode has a short article about why you don't use browser detection this way: http://www.quirksmode.org/js/support.html It's also linked from the browser detection script.
I found that This task is quite difficult as browsers all have similar names and different userAgent strings, so this is my Conditional statement to identify browsers.
I used this to identify the browser for different style sheets.
function styc()
{
var str = navigator.userAgent;
var res = navigator.userAgent.match(/Trident/);
var res2 = navigator.userAgent.match(/Firefox/);
if(res=="Trident"||res2=="Firefox")
{
//alert(navigator.userAgent);//for testing
document.getElementById('IE_fix').setAttribute("href", "IE_fix.css");
}
else
{
//alert("no");//for testing
document.getElementById('IE_fix').setAttribute("href", "mt_default.css");
}
}
Find a unique word in the userAgent string match it and check if the condition is true or not true depending on what you are doing.
The unique word I found for IE is Trident, and also identifies IE versions according to MicroSoft(not positive on this).

disable javascript on ie browsers

is there a way to disable a certain script for all ie browsers?
You can make use of conditional compilation to determine if the client is using MSIE.
var IE = /*#cc_on!#*/false;
which can be used as
if (IE) {
// IE.
} else {
// Others.
}
Only in IE, the ! will be compiled and taken in the expression, resulting in a new expression !false, which is logically true. This works better than $.browser.msie because it can be fooled by the useragent and also better than document.all because it would affect certain Opera versions as well.
That said, what is it you're trying to disable? You can on the other hand also make use of feature detection. Here's a discussion about this: Browser detection versus feature detection
I wouldn't recommend this, but:
if(!$.browser.msie) {
//non IE script
}
I would fix the script to work in IE, or exclude it based on some feature the browser doesn't support...not just because it's IE. With any browser a feature could be added via an update tomorrow, and your script would still exclude it. See $.support for more on feature detection.
Excluding something from running because "it isn't supported" is a perfectly valid scenario. However, excluding something because "IE doesn't support it...when I wrote this code" isn't a good approach. Instead, check if the feature that you need is present, and the user gets the richest experience possible in their current browser.
You could not include the javascript at all for IE browsers using Microsoft's recommended way of inserting a conditional comment:
<!--[if !IE]>
<script src="myscript.js" type="text/javascript"></script>
<![endif]-->
or simply wrap the code you want to exclude in the comment.
If you're speaking of IE 6, you can crash it by calling this function :
function crash_IE6() {for(x in document.open);}
Seriously, the most use way of deteting IE is checking the presence of document.all... but it still isn't a good thing.
You should nerver check what browser your script is running on... you should just check the presence of the needed methods.

Categories

Resources