Writing ECMAScript5 compliant code - javascript

I want to build a library in JavaScript/JScript/ECMAScript...whatever you want to call it, which will target modern standards (HTML5, CSS3, ESv5) with that in mind, any browser that supports the standard! Now I know there are already plenty of useful libraries out there, i.e. jQuery and MooTools. Of course they're great and I already use those where necessary, but I should not be forced to jump on the same bandwagon as every other developer just because it's popular!
So for the sake of the following questions, let us not concern ourselves with 3rd party libraries such as jQuery and MooTools. Lets get down to nitty-gritty JavaScript/JScript/ECMAScript.
Firstly, I asked a question prior to this (What's the difference between JavaScript, JScript & ECMAScript?), as I did not know what the difference was.
Thankfully I concluded the following:
ECMAScript is the language specification. JavaScript and JScript are dialects of ECMAScript.
JavaScript is Mozilla's implementation of ECMAScript.
JScript is Microsoft's implementation of ECMAScript.
OK, that was a nice simple answer wasn't it? But here's some questions which stem from that:
is "JavaScript" supported in non-mozilla browsers, and to what extent?
is "JScript" supported in non-microsoft browsers, and to what extent?
Based on those two questions, I did a little digging and ran a simple test on IE9, FF14 and GC19.
Here is the test code:
<!DOCTYPE html>
<html>
<head>
<title>HTML 5 Template</title>
<script language="JavaScript1.3">
jsver = "1.3";
</script>
<script language="JavaScript1.4">
jsver = "1.4";
</script>
<script language="JavaScript1.5">
jsver = "1.5";
</script>
<script language="JavaScript1.6">
jsver = "1.6";
</script>
<script language="JavaScript1.7">
jsver = "1.7";
</script>
<script language="JavaScript1.8">
jsver = "1.8";
</script>
<script type="text/javascript">
document.write("<B>Your browser supports JavaScript version " + jsver + ".</B>")
</script>
</head>
<body>
</body>
</html>
The results were: IE9 = JSv1.3, FF14 = JSv1.8, GC19 = JSv1.7
OK, then I ran this test, which tests for ECMAScript version 5 support:
http://kangax.github.com/es5-compat-table/#showold
Again using the same browsers (IE9, FF14, GC19), ESv5 seems to be fairly well supported!
Now comes the tricky bit! I come from a Microsoft background, and write software using languages like C#, ASP.NET etc, so naturally, my IDE of choice is Visual Studio (currently 2010). When I look through the JavaScript intellisense I see things like ActiveXObject, Array, Object, etc.
Should I trust VS2010's intellisense?
Where can I find a reference of ESv5 supported objects and features?
How do I detect if a browser supports a particular object or feature?
Is there anything better than VS2010 out there that will help me write compliant ESv5 code?
Is it safe to override implementations of existing objects like Object, Number, Boolean etc, or should I just extend the existing implementation?
Finally, concerning myself with jQuery. Let's say I can't be bothered to write the core compliancy & functionality myself, can I just write my library to sit on top of jQuery...or is this just a copout?

1) Nope. Certainly it won’t restrict to just valid ECMAScript.
2) http://kangax.github.com/es5-compat-table/ is always useful.
3) You can just check to see if it’s defined. E.g.
typeof(Array.isArray) === 'function'; // true in newer browsers, false in IE8
4) Your best bet is to read the spec! Using "use strict"; in your code will also catch some classes of errors and it good practise. More explanation on strict mode at http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
5) Certainly I wouldn’t replace the original objects. If you’re going to extend properties I’d first double-check that a compliant implementation doesn’t already exist. E.g. PrototypeJS added (before browsers implemented it) a document.getElementsByClassName. When browsers started implementing it natively they found out that sites using Prototype were still using the slow JS-based version. The fix was just to wrap Prototype’s definition in a if (document.getElementsByClassName == undefined) { }

2) I find the Overview you provided pretty good. What else do you want?
3) A good library to even out the differences between the browser is ES5-shim. It autodetects the features and provides shims for the browsers who lack support.
4) Always use "use strict"; and a have good editor of your choice which has some kind of code-highlighting and perhaps code-completion. I use the browser consoles or firefox scratchpad (silly name for a good tool) for quick hacking sessions and put it all together in notepad++ (= the IDE of your choice).
5) Augmenting the native javascript objects has been debated a lot and has pros and cons. Prototype and MooTools go this way. jQuery takes the other way and provides a separate object for that. I personally prefer to leave the native (and especially host) objects alone and have your own namespace with the functions you need.

Related

Is it safe to create Custom HTML Tags?

I am reading about a technique wherein you can create custom HTML tags, like so:
<!-- REGISTER CUSTOM ELEMENTS -->
<script type="text/javascript">
var ApplicationContainer = document.registerElement('application-container');
document.body.appendChild(new ApplicationContainer());
</script>
Given there is a variety of browsers & browser-versions out there, I was wondering:
Is it safe to create custom tags yet?
If not, what is the proper work-around?
...I'm just curious, really.
No this is not recommended unless you have some sort of polyfill. It is unsupported in most browsers, see caniuse.
There are a few known polyfills however they do have their setbacks. WebComponents Repository
I wouldn't recommend that. you should be able to implement whatever you need using existing HTML tags. you need to think of your requirements again. do you need a new HTML tag to make it distinctive from existing ones? if yes you can always use data attributes to distinguish it from others. but if you essentially need to create a custom tag, Google developers has a very interesting walk through. hope my answer has been helpful.
According to snuggsi
Web Components ARE ready for production
& Custom Elements v1 has full support for every modern browser
including Internet Explorer 11+ / Edge
It is not immediately clear what you mean by "safe", as that is a rather broad and indefinite term.
#PrisonerZER0 I wouldn't call "Olde browsers" the word "safe". Somewhat of an oxymoron. Even M$ has put IE in a coffin. https://www.microsoft.com/en-us/windowsforbusiness/end-of-ie-support
Us supporting them is only asking for trouble. Thanks for the shout.
I created the snuggsi ツ (https://github.com/devpunks/snuggsi) library as a suite of conventions over the web components/custom elements native browser spec. My philosophy is you shouldn't need to know node, webpack, babel, etc. Should only need to know basic HTML,CSS,JS to be productive in 2017. The following snippet is a perfect example.
Feel free to reach out on github as it seems like you are up to snuff with modern platform development. We won't need these convoluted front end tools where we are going🚀 Feel free to reach out on github so i can help you get started!
<hello-world>
Hello {planet}
</hello-world>
<!-- more info # https://github.com/devpunks/snuggsi -->
<script src=//unpkg.com/snuggsi></script>
<script>
// Element Definition -----------------------------
Element `hello-world`
// Class Description ------------------------------
(class extends HTMLElement {
get planet ()
// "automagic" token binding
{ return 'world 🌎' }
onclick ()
// "automagic" event registration
{ alert (this) }
})
</script>

How to detect if browser is compatible with ES2015 [duplicate]

This question already has answers here:
Javascript ES6 cross-browser detection
(10 answers)
Closed 7 years ago.
I have a big chunk of JS libraries that I should rewrite since it's really old and outdated. So, I decided to come up with a solution where I would just use most of ES2015 features like rest parameters.
The thing is, I am sure all the clients would not have their browser up-to-date and I am confused whether I will face any issue regarding their browser is compatible with my new JS libs.
So, I was wondering if I could detect whether the client browsers are compatible with ES2015. And if not, I would just include my old JS library.
I am looking for a solution like Conditional comments, but I am getting nowhere to solution.
Any help in HTML, JS or PHP is appreciated. Please kindly suggest your advice.
I was wondering if I could detect whether the client browsers are
compatible with ES2015. And if not, I would just include my old JS
library.
You cannot do that, simply because AFAIK there's no browser that fully supports ES2015. Also, you don't really want to maintain two different versions of your code, because it's painful and it could get messy really quick.
The approach nowadays is to use a transpiler, which is sort of a compiler that compiles your ES2015 code to ES5 (the JavaScript that every browser knows). It is still kind of messy, but at least you get to write only one version of your code, and it's ES2015.
I think Babel (formerly 6to5) is the most popular transpiler. You can check out their website for getting started.
As to answer your actual question,
How to detect if browser is compatible with ES2015
You can do that in many ways. I'm not sure what could be the most reliable one, but for example you could simply try on your browser's console:
'Promise' in window
If this statement returns true, then the current browser supports promises, which is a new feature of ES2015, so you could assume that it supports most of the features of ES2015.
This is not enough for most cases though; you may want to be 100% sure that what you're using is not going to throw a SyntaxError in any old browser.
A solution could be to manually check for each feature you want to use. For example, if you need the Fetch API, you could create a function that tells you if the current browser supports it:
function isFetchAPISupported() {
return 'fetch' in window;
}
You can do this for any new API you need. However, if you need something syntactically different, I think your only bet is eval() (as Katana314 suggested). For example, in order to check support for rest parameters you could do:
function isRestSupported() {
try {
eval('function foo(bar, ...rest) { return 1; };');
} catch (error) {
return false;
}
return true;
}
This works great in Firefox, because the rest parameters are supported.
It works as well on Safari, returning false because rest parameters are not supported there yet.

extjs4 Object doesn't support property or method 'indexOf' IE 8 workaround issue

My User defined sort function does not work in IE 8.
Object doesn't support property or method 'indexOf'
roles_store.sort([{
sorterFn: function(v1, v2) {
var order = ['read-only', 'user', 'admin', 'super'],
v1o = order.indexOf(v1.get('role_name')),
v2o = order.indexOf(v2.get('role_name'));
return v1o < v2o ? -1 : 1;;
}
}]);
The following link shows a workaround:
How to fix Array indexOf() in JavaScript for Internet Explorer browsers
I tried replacing indexof with Array.prototype.indexOf
v2o = order.Array.prototype.indexOf (v2.get('role_name'));
I apologize if I missed something here
IE 8 is a little old and it includes an old javascript version. It doesn´t have a lot of very useful methods that we use everyday. I recommend to include the tiny Array prototype extensions library (link). That library allows you to use all the methods (for arrays) that all new browsers (with newer javascript version) include.
You also can use the Extjs methods as Evan suggests (they work well) but you have to have that in mind all the time and most of the snippets and code samples that you find in internet or this site won´t run (you will have to translate them to use extjs methods). Another problem is that your code will works ok in Chrome and FF but not in IE if you not take care.
It is much more easy and safe to include the extensions that I recommend you, that´s what we did in our own project and it was a great solution.
Use Ext.Array.indexOf, it defers to the native indexOf where possible.
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.Array-method-indexOf

How to provide ECMAScript 5 (ES 5)-shim?

ECMAScript Fifth Edition (released December 2009) introduces a bunch of new methods (see this table for details). However, there still are older browsers out there which do not implement those new methods.
Luckily, there exists a convenient script (written in JavaScript) - ES5-shim - which implements those methods manually in environments where they don't exist.
However, I am not sure how to provide ES5-shim... Should I just "give" it to all browsers, like so:
<script src="es5-shim.js"></scipt>
Or should I include a check in order to only "bother" those browsers which really need it, like so:
<script>
if ( !Function.prototype.hasOwnProperty( 'bind' ) ) {
(function () {
var shim = document.createElement( 'script' );
shim.src = 'es5-shim.js';
var script = document.getElementsByTagName( 'script' )[0];
script.parentNode.insertBefore( shim, script );
}());
}
</script>
(I'm using Function.prototype.bind to check if a browser implements all new ECMAScript 5 methods. According to the compatibility table which I linked above, bind is the "last bastion" when it comes to implementing ECMAScript 5 methods.)
Of course, for this shim to be effective, it has to be executed before all other scripts, which means that we want to include the above mentioned SCRIPT elements early in the page (in the HEAD, before all other SCRIPT elements).
So, would this second example be a good way to provide ECMAScript 5-shim to browsers? Is there a better way to do it?
ES5-Shim will only shim parts that the browsers don't implement, so just give it to all browsers. It'll handle the detection of what needs to be shimmed and what doesn't.
But pay attention to the caveats listed on what shims don't work correctly in some instances. I've had issues with that in the past and it causes a ton of pain until you realize the answer was super simple...
This seems to work for me:
<!--[if lt IE 9]><script src="java/es5-shim.min.js"></script><![endif]-->
At present, the solution that works best with ES5-Shim is to use the library in all environments and allow it to detect which features it needs to patch at run-time. It would be even better to deliver it from a community CDN to maximize cross-site cache hits.
That being said, there is an open opportunity to create systems that combines feature detection, agent fingerprinting, and dynamic bundling to automatically generate and deliver targeted shim subsets. The scope of the problem extends far beyond just ES5-Shim and could be applied to all sorts of shims.

JavaScript code completition done right?

I've tried some of the editors/IDEs regularly recommended for coding JavaScript (Aptana, WebStorm, ...) but none of them has a satisfying autocomplete functionality. I'm probably spoiled by Microsoft's IntelliSense for .NET. There is some JavaScript-IntelliSense in WebDeveloper, but that seems to be a stripped-down version. The best I've found so far is WebStorm, but its code completition is easily distracted by imported libraries (offering hundreds of suggestions) and identical function names.
Did I miss an editor/IDE that uses refactoring (or something else) to offer proper code completition, so that it really "knowns" what that variable-name stands for, I just put a dot behind? Or is something like this on its way?
I always recommend Komodo Edit from ActiveState (now up to version 6, with support for HTML 5 and CSS3 as well as recent versions of Javascript, PHP, etc.) Note that you may have to install addons for the languages you're working in, but you should find them through the Mozilla-like Addon manager.
Also supports jQuery and even lets you use jQuery (along with vanilla Javascript or Python) in its powerful macro IDE.
Code completion example:
<script type="application/x-javascript">
var obj = {};
obj.personnel = [{firstName:"John", lastName:"Brick", age:43},
{firstName:"Jane", lastName:"Motte", age:26}
];
// now type obj. and code completion immediately offers you "personnel"
// note: file must be saved for the app to find all members of declared
// variables, but I save about every 10 seconds so it's not a problem
</script>
The best I've found so far is
WebStorm, but its code completition is
easily distracted by imported
libraries (offering hundreds of
suggestions) and identical function
names.
This comment confuses me. If you import the libraries, and your code is using them, why is it bad to include the function names in the code completion suggestions? Wouldn't you want to have jQuery's functions included if you're using it?
If you're using Microsoft's IntelliSense with jQuery, does it stick to its guns and only show JavaScript core functions? Sounds limited to me, unable to be smart when I add libraries.
Or is something like this on it's [sic] way?
It sounds to me like you want a clairvoyant interface. I don't think it is on the way anytime soon.
By the way, "it's" == "it is"; "its" is the possessive.

Categories

Resources