- A shim lets you write the same code across all browsers by implementing a new API in downlevel browsers.
- A polyfill is a shim or collection of shims (and a catchy name).
- A prollyfill is a shim for a proposed API
- A helper helps write cross-browser code where a true API shim/polyfill is not possible.
Note that my general approach to polyfills is not to produce 100% compliant behavior, but to provide a broad subset of functionality so that, where possible, cooperative code can be written to take advantage of new APIs. No assumptions should be made about security or edge cases. It is preferrable to use a shim where it is possible to create one on supported browsers. If not possible, a helper should be used that lets the same code be used in all browsers.
I use these in various pages on my sites; most are by me, or I have at least tweaked them. A more comprehensive list can be found at The All-In-One Entirely-Not-Alphabetical No-Bullshit Guide to HTML5 Fallbacks by Paul Irish.
Bundled together; nearly every page I create needs at least some of these. These will change over time, and going forward I will only target IE8 and later.
- ECMAScript 5 Object, Function, String and Date extras
- Object:
getPrototypeOf
,getOwnPropertyNames
,create
,defineProperty
,defineProperties
,keys
- Function prototype:
bind
- Array:
isArray
- Array prototype:
indexOf
,lastIndexOf
,every
,some
,forEach
,map
,filter
,reduce
,reduceRight
- String prototype:
trim
- Date:
now
- Date prototype:
toISOString
- Object:
XMLHttpRequest
(for IE6-)- Selector API (for IE7-) - adapted from Paul Young
element = document.querySelector(selector)
elementArray = document.querySelectorAll(selector)
- DOM Events
- Where
EventTarget
iswindow
,document
, or any element: EventTarget.addEventListener(event, handler)
- for IE8+EventTarget.removeEventListener(event, handler)
- for IE8+window.addEvent(EventTarget, event, handler)
- helper for IE7- support - adapted from QuirksModewindow.removeEvent(EventTarget, event, handler)
- helper for IE7- support - adapted from QuirksModeEvent.target
Event.currentTarget
Event.eventPhase
Event.bubbles
Event.cancelable
Event.timeStamp
Event.defaultPrevented
Event.stopPropagation()
Event.cancelBubble()
- Where
- DOM Miscellany
document.head
elementArray = document.getElementsByClassName(classNames)
- HTML Web Application APIs (for IE9-)
encodedString = window.btoa(binaryString)
- Base64 EncodebinaryString = window.atob(encodedString)
- Base64 Decode
- HTML5 Infrastructure -
classList
spec,relList
spectokenList = elem.classList
- for IE8+tokenList = elem.relList
- for IE8+tokenList = window.getClassList(element)
- helper for IE7- supporttokenList = window.getRelList(element)
- helper for IE7- supporttokenList.length
tokenList.item(index)
tokenList.contains(token)
tokenList.add(token)
tokenList.remove(token)
tokenList.toggle(token)
- W3C Timing control for script-based animations - demo page
id = window.requestAnimationFrame()
window.cancelAnimationFrame(id)
- Efficient Script Yielding
id = setImmediate(callback, args...)
clearImmediate(id)
dataset
anddata-*
attributes spec (for IE8+, not available in IE7-)str = element.dataset[key]
- yields undefined if data-key attribute not presentelement.dataset[key] = str
- fails unless data-key attribute already present
- JavaScript 1.X String Extras
- String prototype:
trimLeft
,trimRight
,quote
- String prototype:
"Harmony" is the aspirational term for the future of ECMAScript (the standardized version of JavaScript) beyond ES5. The standardization of ES6 is currently in progress. This will attempt to track the evolving spec, so may change at any time.
In the ES6 Drafts:
- Object:
assign()
,is()
,setPrototypeOf()
- Number:
EPILON
,MAX_INTEGER
,parseInt()
,parseFloat()
,isFinite()
,isNaN()
,isInteger()
,toInteger()
- Number prototype:
clz()
- String:
fromCodePoint()
- String.prototype:
codePointAt()
,repeat()
,startsWith()
,endsWith()
,contains()
- Math:
log10()
,log2()
,log1p()
,expm1()
,cosh()
,sinh()
,tanh()
,acosh()
,asinh()
,atanh()
,hypot()
,trunc()
,sign()
,cbrt()
,imul()
- Array:
of()
,from()
- Array prototype:
find()
,findIndex()
,entries()
,keys()
,values()
,@@iterator()
- Map:
clear()
,delete()
,forEach()
,get()
,has()
,entries()
,keys()
,set()
,size
,values()
,@@iterator()
- Set:
add()
,clear()
,delete()
,forEach()
,has()
,size
,values()
,@@iterator()
- WeakMap (intrusive; modifies valueOf property of key):
clear()
,delete()
,get()
,has()
,set()
Not yet approved:
- Number:
compare()
- Array prototype:
pushAll()
,contains()
ref - String prototype:
@@iterator()
ref - Dict:
keys(dict)
,values(dict)
,entries(dict)
dict()
is shortcut forObject.create(null)
- Symbol:
Symbol
- No security, just creates an object with a unique string representation.
typeof
will incorrectly report"object"
- No security, just creates an object with a unique string representation.
Helpers:
forOf(o, function(i) { ... })
- sincefor (i of o) { ... }
can't be polyfilled. Uses iterators, so works with arrays, maps, sets, and strings, via implicit @@iterator and explicit iterators returned by keys/values/entries methods and functions.
Proposed for ES6 - http://wiki.ecmascript.org/doku.php?id=harmony:binary_data
script - unit tests - spec
ArrayBuffer
Uint8Array
,Int8Array
,Uint16Array
,Int16Array
,Uint32Array
,Int32Array
,Float32Array
,Float64Array
DataView
script - unit tests - draft spec - See script for cross-browser quirks
var url = new URL(url, base);
var value = url.getParameter(name);
var valueArray = url.getParameterAll(name);
url.appendParameter(name, valueOrValues);
url.clearParameter(name);
var nameArray = url.parameterNames;
URL objects have properties:
protocol
host
hostname
port
pathname
search
hash
filename
href
script - demo page - draft spec
// In your keydown/keyup handler, call:
window.identifyKey(keyboardEvent);
// This adds the following properties to keyboardEvent:
keyboardEvent.code
keyboardEvent.location
// You can get a label for the key using:
KeyboardEvent.queryKeyCap(code);
script - spec - adapted from Remy Sharp
storage = window.localStorage
storage = window.sessionStorage
storage.clear()
valueString = storage.getItem(keyString)
valueString = storage.key(index)
storage.removeItem(keyString)
storage.setItem(keyString, valueString)
storage.length
script - demo page - spec - uses freegeoip.net
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
var watchId = navigator.geolocation.watchPosition(successCallback, errorCallback, options);
navigator.geolocation.clearWatch(watchId);
script - spec - just for kicks; you probably don't want to use this
script - unit tests - de facto standard in modern browsers based on FireBug Console API
console.log(messageObject, arguments...); // and variations: debug, info, warn, error
console.assert(assertion, messageObject, arguments...);
console.count(name);
console.time(name); console.timeEnd(name);
console.group(name); console.groupEnd();
console.trace();
console.clear();
script - Adam Barth's Cookie API proposal - abandoned
var cookie = document.getCookie(name, callback);
alert(cookie.name);
alert(cookie.value);
var cookieArray = document.getAllCookies(callback);
document.setCookie(cookie, errorCallback);
document.deleteCookie(name, errorCallback);
Creates a native DOMException of the specified type if possible, otherwise a similar looking object. Useful when implementing other polyfills.
exception = DOMException.create(code)
script - unit tests - used for a few C-to-JavaScript porting projects
var str = sprintf("Foo %s bar %d", "hello", 123);