This is not a new topic, but I am curious how everyone is handling either .js or .css that is browser specific.
Do you have .js functions that have if/else conditions in them or do you have separate files for each browser?
Is this really an issue these days with the current versions of each of the popular browsers?
It's a very real issue. Mostly just because of IE6. You can handle IE6-specific CSS by using conditional comments.
For JavaScript, I'd recommend using a library that has already done most of the work of abstracting away browser differences. jQuery is really good in this regard.
Don't write them?
Honestly, browser specific CSS is not really necessary for most layouts - if it is, consider changing the layout. What happens when the next browser comes out that needs another variation? Yuck. If you have something that you really need to include, and it doesn't seem to be working in one browser, ask a question here! There are lots of great minds.
For JS, there are several frameworks that take care of implementing cross-browser behaviour, such as jQuery (used on this site).
The IE conditional comments have the downside of an extra file download. I prefer to use a couple of well-known CSS filters:
.myClass {
color: red; // Non-IE browsers will use this one
*color: blue; // IE7 will see this one
_color: green; // IE6 and below will see this one
}
(Yeah, it won't validate, but last I checked, our money comes from users and advertisers, not from the W3C.)
It is still an issue these days for CSS not working in all browsers (mostly IE6/7).
I've never needed a separate JS file for anything I've worked on. If you are using a JS library (jQuery, YUI, Prototype, etc), 99% of your browser incompatibilities will be taken care of.
As for CSS, I prefer to stick my browser-specific fixes in the same CSS file. It makes it a lot easier to debug when you only have to look in 1 place for your styling. You could spend hours debugging something only to find out the bug is caused by your 10 line browser-specific stylesheet.
It's also better from a performance perspective to only have 1 CSS and 1 JS file.
Use what is known as "feature detection".
For example, if you want to use document.getElementsByClassName, do the following:
if(document.getElementsByClassName) {
// do something with document.getElementsByClassName
} else {
// find an alternative
}
As for CSS, you should largely be good if you use standards, except in IE. In IE, use conditional comments - it's the method recommended by the guys at Microsoft.
Personally I've mostly used conditional comments as noted above.
In the Stackoverflow podcast, though, Jeff indicated that Stackoverflow is using Yahoo's CSS Reset, which I'd never heard of. If it does what it's advertised to do it seems that would resolve many (most? all?) browser-based CSS differences; I don't see anything indicating conditional commenting in the Stackoverflow html source, at least. I'm definitely going to play with it on my next web project and would love to hear anyone's experiences with it.
As far as Javascript; as has already beed said, use your favorite JS Framework...
I use a framework to handle 99% of the xbrowser stuff.
For everything not covered in the framework, I'd use a if/else or a try/catch.
Both if/else and separate files, it depends on the complexity of the site.
There are definitely still incompatibilities between browsers, so consider letting a JavaScript Framework do the dirty work for you...
jQuery
http://jquery.com/
Dojo
http://www.dojotoolkit.org/
Script.aculo.us
http://script.aculo.us/
Prototype
http://prototypejs.org/
I use the built in functions of jQuery for the actual detection:
jQuery.each(jQuery.browser, function(i, val) {});
As for organization, that would depend on your application. I think putting this in an initialization code and then using the detection where you need it would be best. I still have issues where I have to detect Explorer on occasion. For example, when using jQuery, I have found that the parent() and next() functions will sometimes have different meanings in Explorer compared to Firefox.
Internet Explorer has conditional constructs like
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->
that will let you bring in specific style sheets and JavaScript just for IE. I consider this a solution of last resort if there are no standards-compliant ways to deal with a problem.
If you are doing ASP.Net development, you can also use Device Filtering (which I just learned about here on Stack Overflow today).
You can use it on your Page Directives to link in different skins, master pages, or CSS files, but you can also use on ASP.Net server control attributes, like this:
<asp:Label runat="server" ID="labelText"
ie:CssClass="IeLabelClass"
mozilla:CssClass="FirefoxLabelClass"
CssClass="GenericLabelClass" />
That example is, of course, a bit extreme, but it does let you work around some nasty browser inconsistencies while using only a single CSS file.
I also second the idea of using a CSS reset file and definitely use a library like jQuery instead of reinventing the wheel on JavaScript event and DOM differences.
I think conditional comments are great for style sheets but they can also be used for javascript/jquery.
Since the .browser has been deprecated and now removed from jquery 1.9 (?) using conditional comments is a pretty good way to do browser specific javascript.
here is my quick example:
1 - Place a conditional comment somewhere on the page. I personally put it right after the body tag. I've seen people use it on the actual body or html but that brings back the IE8/9/10 comparability view button and you want to avoid this if possible.
<!--[if lt IE 9]><div class="ie8-and-below"></div><![endif]-->
2 - then use jquery to check if our IE specific container is there.
if ($("div").hasClass("ie8-and-below")) {
//do you JS for IE 8 and below only
}
3 - (optional) set your target comparability and put something like:
<meta http-equiv="X-UA-Compatible" content="IE=10" />
right after the <head> tag. (it has to be the very 1st thing after the opening <head>).
This will turn off the compatibility button in ie10/9/8 if the rest of your page is properly coded. It's a good fail safe if you have sections that require comparability mode, other ways you may trigger your JS if running a newer browser in compatibility.
Note: As of the date of this post the http-equiv does not validate W3C standards but it's a very useful tag which has been adopted by the home pages of google and microsoft among others. I think it's only because W3C is a bit behind on adopting it.
Related
I'd like to use autofocus="autofocus" in my code, but since some browsers don't support this yet, I was thinking of adding some JS code, which would search for an element with such a tag, and focus it with JS. But since this seems to be a common requirement, I wonder if there are any ready libraries, which can take care of at least some HTML5 annoyances with older browsers?
I believe the correct answer would be not quite. Modernizr 2.0 (including html5shim) gives us semantic elements of html5 (actually the html5shim does that) and great feature detection which you can use for graceful js fallback.
In you case It would be using jQuery .focus() with something like:
if (!Modernizr.autofocus){
$('input[autofocus=""]').focus();
}
more examples here
If older browsers don't support certain advanced features, then I would say follow progressive enhancement and don't worry about it. So long as the core functionality of your site—ordering products, or whatever—works across the board, then don't be afraid to add in shiny html5 features for the benefit of your users with good browsers.
Putting in clunky/third-party code to force IE6 and 7 to behave in a civilized manner will potentially be a lot of work for you, will be prone to bugs, and won't even give you too much of a payoff since the folks using IE6 probably won't be looking over the shoulders of Chrome users to see a nicer version of your site there.
Here are the slides (from a jQuery conference) that really drove this home for me.
The role of Modernizr (previously mentioned) is to do feature detection, to determine what HTML 5 features are available. Modernizr doesn't automatically make unavailable HTML 5 features available, but it does make it possible for you to conditionally load scripts (commonly referred to as polyfills) to add those features. In the case of autofocus, the html5support library should provide what you need, and you can use Modernizr's conditional loading to only load it if needed.
Users of libraries like jQuery say that they implement such a features.
I don’t recommend it anyway, try to code the minimum functions you need by yourself.
Take also a look at http://www.modernizr.com/.
I'm reviewing some html produced by an overseas development shop for us. They are using comments inside their external script loading tags - so far as i'm aware this was only useful for very old javascript unaware browsers who used to render the scripts as text - is there any modern purpose for this or is it now completely redundant?
<script type="text/javascript" src="path/to/file.js"><!--//--></script>
Thanks in advance
//Update after comments below: It turns out that the comments were hacking a problem in the Content Management System where it would render the tag as
<script type="text/javascript" src="path/to/" />
without the comments present - so the answer is that they nolonger have any use in general web development but there are some specific circumstances where they may be useful. Kudos to Caspar Kleijne for pointing this out.
No, it's not useful any more.
It was used way back when there still existed browsers that were shipped before Javascript existed. Nowadays every browser is aware of the existance of Javascript, even if they don't support it.
If someone still would have such an ancient browser isntalled, your page will look so terribly crappy in it that it doesn't make any difference.
Since you are including it from an external file, there should be no use at all for it.
This always depends on your target group. You could check your site's stats to see if there's a significant number of people using some old old browsers and then decide. It's rather improbable you'll find many, if any.
Personally, I don't comment out my JavaScript code.
But on a sidenote - using <noscript> is still important, maybe now more than ever in the time of ajax-driven sites.
It isn't necessary going forward and is often left off, though it may be an attempt at XHTML standardization, where CDATA is typically used. This question has lots more information: When is a CDATA section necessary within a script tag?
Whether intended for XHTML or for old-browser support, it isn't hurting anything, though it almost definitely not helping. It could help to support some archaic browsers, but if you're not testing against those specifically, your site won't work properly anyhow. Leave it off unless you are using XHTML.
I'm not a JavaScript wiz, but is it possible to create a single embeddable JavaScript file that makes all browsers standards compliant? Like a collection of all known JavaScript hacks that force each browser to interpret the code properly?
For example, IE6 does not recognize the :hover pseudo-class in CSS for anything except links, but there exists a JavaScript file that finds all references to :hover and applies a hack that forces IE6 to do it right, allowing me to use the hover command as I should.
There is an unbelievable amount of time (and thus money) that every webmaster has to spend on learning all these hacks. Imagine if there was an open source project where all one has to do is add one line to the header embedding the code and then they'd be free to code their site per accepted web standards (XHTML Strict, CSS3).
Plus, this would give an incentive for web browsers to follow the standards or be stuck with a slower browser due to all the JavaScript code being executed.
So, is this possible?
Plus, this would give an incentive for web browsers to follow the standards or be stuck with a slower browser due to all the JavaScript code being executed.
Well... That's kind of the issue. Not every incompatibility can be smoothed out using JS tricks, and others will become too slow to be usable, or retain subtle incompatibilities. A classic example are the many scripts to fake support for translucency in PNG files on IE6: they worked for simple situations, but fell apart or became prohibitively slow for pages that used such images creatively and extensively.
There's no free lunch.
Others have pointed out specific situations where you can use a script to fake features that aren't supported, or a library to abstract away differences. My advice is to approach this problem piecemeal: write your code for a decent browser, restricting yourself as much as possible to the common set of supported functionality for critical features. Then bring in the hacks to patch up the browsers that fail, allowing yourself to drop functionality or degrade gracefully when possible on older / lesser browsers.
Don't expect it to be too easy. If it was that simple, you wouldn't be getting paid for it... ;-)
Check out jQuery it does a good job of standardizing browser javascript
Along those same lines explorercanvas brings support for the HTML5 canvas tag to IE browsers.
You can't get full standards compliance, but you can use a framework that smooths over some of the worst breaches. You can also use something called a reset style sheet.
There's a library for IE to make it act more like a standards-compliant browser: Dean Edwards' IE7.
Like a collection of all known
javascript hacks that force each
browser to interpret the code properly
You have two choices: read browser compatibility tables and learn each exception a browser has and create one yourself, or use avaiable libraries.
If you want a javascript correction abstraction, you can use jQuery.
If you want a css correction abstraction, you can check /IE7/.
I usually don't like to use css corrections made by javascript. It's another complexity to my code, another library that can insert bugs to already bugged browsers. I prefer creating conditional statements to ie6, ie7 and such and create separate stylesheets for each of them. This approach works and doesn't generate a lot of overhead.
EDIT: (I know that we have problems in other browsers, but since IE is the major browser out there and usually we need really strange hacks to make it work, css conditional statements is a good approach IMO).
Actually you can,there are lots of libraries to handle this issue. From the start of the time, javascript compliance issue always was a problem for developers and thanks to innovative ones who developed libraries to get over this problem...
One of them and my favorite is JQuery.
Before JavaScript 1.4 there was no global arguments Array, and it is impossible to implement the arguments array yourself without a highly advanced source filter. This means it is going to be impossible for the language to maintain backwards-compatibility with Netscape 4.0 and Internet Explorer 4.0. So right out I can say that no, you cannot make all browser standards compliant.
Post-netscape, you can implement nearly all of the features in the core of the language in JavaScript itself. For example, I coded all methods of the Array object in 100% JavaScript code.
http://openjsan.org/doc/j/jh/jhuni/StandardLibrary/1.81/index.html
You can see my implementation of Array here if you go to the link and then go down to Array and then "source."
What most of you are probably referring to is implementing the DOM objects yourself, which is much more problematic. Using VML you can implement the Canvas tag across all the modern browsers, however, you will get a buggy/barely-working performance in Internet Explorer because VML is markup which is not a good format for implementing the Canvas tag...
http://code.google.com/p/explorercanvas/
Flash/Silverlight: Using either of these you can implement the Canvas tag and it will work quite well, you can also implement sound. However, if the user doesn't have any browser plugins there is nothing you can do.
http://www.schillmania.com/projects/soundmanager2/
DOM Abstractions: On the issue of the DOM, you can abstract away from the DOM by implementing your own Event object such as in the case of QEvent, or even implementing your own Node object like in the case of YAHOO.util.Element, however, these usually have some subtle changes to the standard API, so people are usually just abstracting away from the standard, and there is hundreds of cases of libraries that abstract away.
http://code.google.com/p/qevent/
This is probably the best answer to your question. It makes browsers as standards-compliant as possible.
http://dean.edwards.name/weblog/2007/03/yet-another/
We are developing a web application that will be sold to many clients. There is already one client (a bank) which has decided that it will buy the product once it is ready. Unfortunately due to some miscommunication it came out rather late that the only browser they use is IE6. The application was already started with the thought in mind that it does not need to support anything else below IE7. The results are pretty good too - it's fully useable on IE7/FF/Opera/Safari. Haven't tested on Chrome, but expect little problems there. Unfortunately there is now the IE6 requirement after all...
The application isn't too far developed yet, and the design is pretty much OK, so the change isn't that horrible. Still, it'll take some work.
A nice thing about IE6 is that it supports two nonstandard and very helpful features. First is conditional comments, which lets me include some CSS/JS files only for IE6. Second is CSS expressions. That is, things like this:
input
{
background-color: expression(this.type='text'?'silver':'');
}
In essence it binds CSS values to JavaScript expressions. This allows to easily emulate many CSS features that IE6 does not support natively, and could lighten my burden considerably.
Unfortunately IE is infamous for its JavaScript performance. I'm worried that using too many of these expressions might slow it down to a crawl. I also have no idea what computers the bank is using. Since it's a pretty big one, I'd expect a wide variety in all their branch offices. I don't expect to use anything much there - some simple math, ternary operators and looking at this element's/parent element's properties. Still there would be a couple dozen of these in the IE6_override.CSS file.
Can this be a problem?
Added: Blah, this was what I was afraid of. OK, will see how much I can use other hacks to get around the shortcomings. Thanx, people!
https://developer.yahoo.com/blogs/ydn/high-performance-sites-rule-7-avoid-css-expressions-7202.html
Turns out you might want to avoid using these, they are dangerous.
Expressions are re-evaluated on many page events, which has the potential to slow down entire page performance when used too liberally. (And yet still, they can't respond to all events that might cause them to need re-evaluating.)
MS have admitted expression() was a mistake, and are removing it from future browsers.
There are generally better individual JavaScript workarounds for IE6's various CSS shortcomings.
It is rather sad that so many companies are still sticking with the dire IE6. Maybe if you deliver the project late they'll have upgraded by then!
It is possible to make IE expressions perform optimally, not only to avoid things like continuous re-evaluation, but to also hook your desired style to IE-specific classnames, therefore making your IE-Specific CSS easier to maintain (as the expressions themselves are disgusting):
input
{
1:expression(this.executedExpressions ? void 0 : this.className += (this.type == 'text' ? ' ie-text' : ''));
2:expression(this.executedExpressions = true);
}
input.ie-text
{
background-color:silver;
}
If you're going to use IE expressions at all, this is the best way. (I really ought to write a thorough article about it).
Unfortunately CSS expressions are very poor performance wise, as the result is calculated constantly, all the time the page is loaded, not just when the page is first loaded. If you have to use expressions then you'd be better off use using standard JavaScript with an onLoad event.
See this article for more info: http://www.robertnyman.com/2007/11/13/stop-using-poor-performance-css-expressions-use-javascript-instead/
I'd suggest you to switch to any JS Framework which supports CSS Selectors so you can emulate the behaiviour of CSS expressions
you can test JS Frameworks performance if you open this URL on IE6
http://slicktest.perrohunter.com
cheers
Yes, expressions are realy slow in IE period. Find ways to avoid them.
I haven´t tried it myself, but IE7-js looks promising. It claims to make IE6 compatible with IE7
Edit: By the way, to just add some styles for IE6, you can also use
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" media="screen" href="ie6styles.css" />
<![endif]-->
And you can always use jquery to set css properties dynamically in all browsers including IE6.
If you do have to use them, the techniques found at One-time execution of IE CSS expressions will help with the performance (but not security) issues.
After hours of debugging, it appears to me that in FireFox, the innerHTML of a DOM reflects what is actually in the markup, but in IE, the innerHTML reflects what's in the markup PLUS any changes made by the user or dynamically (i.e. via Javascript).
Has anyone else found this to be true? Any interesting work-arounds to ensure both behave the same way?
I use jQuery's .html() to get a consistent result across browsers.
I agree with Pat. At this point in the game, writing your own code to deal with cross-browser compatibility given the available Javascript frameworks doesn't make a lot of sense. There's a framework for nearly any taste (some really quite tiny) and they've focused on really abstracting out all of the differences between the browsers. They're doing WAY more testing of it than you're likely to.
Something like jQuery or Yahoo's YUI (think how many people hit the Yahoo Javascript in a day and the variety of browsers) is just way more road-tested than any snippet you or I come up with.
using a good library is a great way to get around browser inconsistencies, and jquery is the one that I typically recommend - and if you're running into issues altering the elements in a form in particular, jquery boasts a few really useful plugins focused specifically on form manipulation and evaluation.
Using prototype and the $("thisid") syntax instead of document.getElementById("thisid") might do the trick for you. It worked for me.