Code Monkey home page Code Monkey logo

polyfill's Introduction

polyfill - JavaScript and Web Polyfills

This is a collection of polyfills covering web platform features, from those defined as part of the ECMAScript standard to new web browser functionality. Most are for features shipping in major browsers. A few are experimental and called out as such, subject to change at any time.

My philosophy is that it's better to write future-looking code that takes advantage of new Web platform APIs where possible, and fill in the gaps with polyfills. There is no effort to produce 100% compliant behavior, or to completely hide differences in browser behavior.

I use these in various pages on my sites; most are by me, or I have at least tweaked them. A more comprehensive list of polyfills can be found at The All-In-One Entirely-Not-Alphabetical No-Bullshit Guide to HTML5 Fallbacks by Paul Irish.

Getting the Code

You're already here! Great, just download it, or use:

git: git clone https://github.com/inexorabletash/polyfill.git

bower: bower install js-polyfills

npm: npm install js-polyfills

It is not packaged as Node.js module(s); there's nothing to require(), this is just for distribution.

Or just include scripts directly in your page via CDN (c/o RawGit):

<script src="https://cdn.rawgit.com/inexorabletash/polyfill/$TAGNAME/polyfill.min.js"></script>

(look at Releases for the tag name, e.g. "v1.2.3")

Files

The polyfills are roughly split up into files matching 1:1 with Web standards (specifications, living standards documents, etc). So there is html.js for HTML, dom.js for DOM, etc.

Since I generally use several in my hobby projects, bundled/minified versions are available:

Minification is done via https://github.com/mishoo/UglifyJS2

Some of the files use console.assert() calls to catch bugs during development. These are automatically removed from the included minified versions. If you use your own minifying processor it may cause to assertions to appear when unnecessary function names are stripped. You can safely remove these lines as part of a build step (e.g. using grep -V), or use a minifier that does this automatically. For UglifyJS2 the option is: drop_console

ECMAScript / JavaScript Polyfills

ECMAScript 5 - Previous standard, supported by browsers circa 2012..

ECMAScript 2015 - Previous standard, supported by browsers circa 2016.

ECMAScript 2016 - Previous standard, supported by browsers circa 2017.

ECMAScript 2017 - Most recent standard. Implementation in progress or complete in latest browsers.

ECMAScript proposed - Proposals for future editions of the standard. Here there be dragons.

JavaScript 1.X String Extras - ref

  • String prototype: trimLeft, trimRight, quote

HTML

script - tests - living standard

  • document.head (for IE8-)
  • 'shiv' of newer HTML elements (section, aside, etc), to fix parsing (for IE8-)
  • dataset and data-* attributes spec (for IE8+, not available in IE7-)
    • str = element.dataset[key] - yields undefined if data-key attribute not present
    • element.dataset[key] = str - fails unless data-key attribute already present
  • Base64 utility methods (for IE9-)
    • encodedString = window.btoa(binaryString) - Base64 Encode
    • binaryString = window.atob(encodedString) - Base64 Decode
  • Animation Frames - demo page
    • id = window.requestAnimationFrame()
    • window.cancelAnimationFrame(id)

DOM

script - tests - living standard

  • Selectors (for IE7-) - adapted from Paul Young
    • element = document.querySelector(selector)
    • elementArray = document.querySelectorAll(selector)
  • elem.matches(selector) (for IE, Firefox 3.6, early Webkit and Opera 15.0)
  • elementArray = document.getElementsByClassName(classNames) (for IE8-)
  • e = element.nextElementSibling, e = element.previousElementSibling (for IE8)
  • Node constants: Node.ELEMENT_NODE, etc (for IE8-)
  • DOMException constants: DOMException.INDEX_SIZE_ERR (for IE8-)
  • Events (for IE8)
    • Where EventTarget is window, document, or any element:
      • EventTarget.addEventListener(event, handler) - for IE8+
      • EventTarget.removeEventListener(event, handler) - for IE8+
    • Event: target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, stopPropagation(), cancelBubble()
  • Non-standard Event helpers for IE7- - adapted from
  • Custom Events
  • QuirksMode
    • window.addEvent(EventTarget, event, handler)
    • window.removeEvent(EventTarget, event, handler)
  • DOMTokenList - classListspec, relListspec
    • DOMTokenList: length, item(index), contains(token), add(token), remove(token), toggle(token)
    • tokenList = elem.classList - for IE8+
    • tokenList = elem.relList - for IE8+
    • Non-standard helpers for IE7-:
      • tokenList = window.getClassList(element)
      • tokenList = window.getRelList(element)
  • ParentNode: node.prepend(nodes...), node.append(nodes...)
  • ChildNode: node.before(nodes...) , node.after(nodes...) , node.replaceWith(nodes...) , node.remove()

Fetch

script - tests - living standard

Example:

fetch('http://example.com/foo.json')
  .then(function(response) { return response.json(); })
  .then(function(data) { console.log(data); });

Supported:

  • Headers: new Headers(), append(name, value), delete(name), get(name), getAll(name), has(name), set(name, value), [Symbol.iterator]()
  • Body: arrayBuffer(), blob(), formData(), json(), text() - but conversions are limited
  • Request: new Request(input, init), method, headers, body, url
  • Response: new Response(body, init), headers, url, status, statusText, body
  • fetch(input, init)

XMLHttpRequest

script - tests - living standard

CSS OM

script - spec

Polyfill for width and height in getBoundingClientRect() in IE8-

URL API

script - tests - living standard

var url = new URL(url, base);
var value = url.searchParams.get(name);
var valueArray = url.searchParams.getAll(name);
url.searchParams.append(name, valueOrValues);
url.searchParams.delete(name);

var p = new URLSearchParams('a=1&b=2');
  • URL: href, origin, protocol, username, password, host, hostname, port, pathname, search, searchParams, hash
  • URLSearchParams: append(name, value), delete(name), get(name), getAll(name), has(name), set(name, value), entries(), keys(), values(), forEach(callback) and [Symbol.iterator]() (if defined)

Uncommon Polyfills

The following are of limited use and are not included in the web.js / polyfill.js bundled versions.

Timing

script

Keyboard Events

script - demo page - draft spec (also)

KeyboardEvent: code, key, location, KeyboardEvent.queryKeyCap(code)

IE7- only: Call window.identifyKey(keyboardEvent); in keydown/keyup handlers before accessing above properties.

more details

Geolocation API

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);

Obsolete

Obsolete and Unmaintained Polyfills

polyfill's People

Contributors

brettz9 avatar bytesnz avatar caridy avatar feesler avatar hzr avatar inexorabletash avatar jahson avatar jakechampion avatar lellimecnar avatar lukaszzdanikowski avatar markadell avatar mickaelvieira avatar neversettleninja avatar rianby64 avatar sendyhalim avatar stuartpb avatar teohhanhui avatar triblondon avatar yaffle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

polyfill's Issues

Licence

Hi!

“Public Domain” is not a licence, and is questionable in some places. Would you be willing to add the following to the licence file:

「In countries where the Public Domain status of the work may not be valid, its author hereby grants a copyright licence to the general public to deal in the work without restriction and permission to sublicence derivates under the terms of any (OSI approved) Open Source licence.」

That would enable us Europeans to use your code. Thanks!

Error in demos/geo.html with Internet explorer 7

function locate(lat, long) {
var map = $("#map");
var x = map.offsetWidth * ((long + 180) % 360) / 360;
var y = map.offsetHeight * (90 - lat) / 180;
var locator = $("#locator");
locator.style.display = '';
// Error: No se puede obtener la propiedad 'style' de referencia nula o sin definir
// Error: Unable to get the 'style' property null reference or undefined
polyfill error ie7

locator.style.left = String(x) + 'px';
locator.style.top = String(y) + 'px';
}

Imprecise roundings

  • unpackFloat32(packFloat32(3.4028235677973366e+38)) should == Infinity, not 1.7014118346046923e+38
  • unpackFloat32(packFloat32(7.006492321624085e-46)) should be zero

ES6: Missing Methods

  • "toMethod" in Function.prototype - unclear it's worth it
  • "raw" in String - not particularly useful, but could just escape unprintables
  • "normalize" in String.prototype - too big, but could make it a no-op
  • "split" in RegExp.prototype - easy
  • "from" in Uint8ClampedArray - typo in applicator ("Uint8ArrayClamped")
  • "of" in Uint8ClampedArray
  • "copyWithin" in Uint8ClampedArray.prototype
  • "entries" in Uint8ClampedArray.prototype
  • "every" in Uint8ClampedArray.prototype
  • "fill" in Uint8ClampedArray.prototype
  • "filter" in Uint8ClampedArray.prototype
  • "find" in Uint8ClampedArray.prototype
  • "findIndex" in Uint8ClampedArray.prototype
  • "forEach" in Uint8ClampedArray.prototype
  • "indexOf" in Uint8ClampedArray.prototype
  • "join" in Uint8ClampedArray.prototype
  • "keys" in Uint8ClampedArray.prototype
  • "lastIndexOf" in Uint8ClampedArray.prototype
  • "map" in Uint8ClampedArray.prototype
  • "reduce" in Uint8ClampedArray.prototype
  • "reduceRight" in Uint8ClampedArray.prototype
  • "reverse" in Uint8ClampedArray.prototype
  • "slice" in Uint8ClampedArray.prototype
  • "some" in Uint8ClampedArray.prototype
  • "sort" in Uint8ClampedArray.prototype
  • "values" in Uint8ClampedArray.prototype
  • "keys" in Set.prototype - easy

harmony.js -> es6.js, add es7.js

  • es6.js: Remove anything not approved from es6
  • es7.js: Create it

Add the ES7 proposals being championed:

  • Object.values()
  • Object.entries()
  • Array.prototype.contains()
  • Object.getOwnPropertyDescriptors()
  • RegExp.escape
  • String.at()
  • String.lpad(), String.rpad()

ES7 proposals now tracked at: https://github.com/tc39/ecma262

And should probably:

  • Move es7.js to experimental folder

typedarray.js the browser stop responding

Hi!

I'm working on an asmjs project, and I tried to use your typedarray.js where TypedArrays are not supported. But when I run the project, the older browsers stop responding.

var space = 4*1024*1024; // 4MB
var MEM = new ArrayBuffer(space);

(function(stdlib, foreign, heap) {
    "use asm";

    var HEAP8 = new stdlib.Uint8Array(heap);

    function main() {
        // ...
    }

    return {main:main};
}(window, {}, MEM)).main();

[enhancement] Add missing bower.json.

Hey, maintainer(s) of inexorabletash/polyfill!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library inexorabletash/polyfill is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "inexorabletash/polyfill",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Uint8Array crashes IE9

Hello,

can you check out the Uint8Array because when I use it to convert a pdf file with this steps:

var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}

IE9 crashes when executing this line:
var ia = new Uint8Array(ab);

PS: ArrayBuffer works great.

Thanks

Math.clz32

Per TC39, Number.prototype.clz() => Math.clz32()

KeyboardEvent.key polyfill

I was rather excited to see an up-to-date KeyboardEvent polyfill, but was surprised that key was not implemented.

Firefox 37 is set to support this properly and chrome just had a commit a couple days ago in master, so this is still not widely supported. I see that char and code are supported, but key feels a lot more natural in my application.

It would be nice to have this.

iteration over Map

  var map = new Map();
  map.set('a', 1);
  map.set('b', 2);
  map.set('c', 3);
  map.set('d', 4);

  var keys = [];
  var iterator = map.keys();
  keys.push(iterator.next());
  map["delete"]('a');
  map["delete"]('b');
  map["delete"]('c');
  map.set('e');
  keys.push(iterator.next());
  keys.push(iterator.next());

  console.log(keys);

this code throws StopIteration, but according to spec keys should be equal to ['a', 'd', 'e']

ES6: Map ctor initializer

23 July 2013 TC39 consensus:

  • Map contructor, accepts optional initializer
  • If initializer undefined, creates an empty map
  • If initializer defined, invoke the @@iterator to create the entries from.
    • For each entry, check if non-null object, throw if not (If Type(map) is not Object then, throw a TypeError exception.)
    • pull off the 0 and 1 property
    • make 0 a key and 1 value
    • No check for duplicate keys

URL: base and bad URL

From spec
1.

Constructor(USVString url, optional USVString base = "about:blank")
If url is failure, return failure.

In other words new URL('') should throw an exception like Firefox

ES6 Final Tweaks

Per https://twitter.com/awbjs

  • ES6 WeakMap and WeakSet clear methods eliminated
  • ES6 final tweaks #2: String.prototype.contains renamed to String.prototype.includes
  • ES6 final tweaks #3: Symbols @@match, @@replace, @@search, @@split replace string names as double dispatch targets in RegExp.prototype
  • ES6 final tweak #4: added RegExp.prototype.flags for accessing flags string. Facilitates RegExp subclasses that add flags.
  • ES6 final tweaks #5: new RegExp(aRegExp, flags) no longer throws. Instead clones first argument but with supplied flags.
    • Can't usefully polyfill a constructor
  • ES6 final tweaks #6: at the top level of a module, the this binding evaluates to undefined.
    • Can't polyfill modules
  • ES6 final tweaks #7: Array.isArray(new Proxy([ ], { })) returns true.
    • Can't polyfill proxies
  • ES6 final tweaks #8: Smalltalk-like species pattern used in Array methods, etc. to determine constructor for derived objects. let derived = new obj.constructor.species();

The smallest 32 bit float should not truncate to zero

var minFloat32 = 1.401298464324817e-45;
var truncated = packFloat32(unpackFloat32(-minFloat32 / 2 - Math.pow(2, -202)));
assert(truncated == -minFloat32) // fails

I don't understand the math at all, I've just collected some test cases :-/ so thanks for reasoning through it for me :-)

XHR Event polyfill

XMLHttpRequest, in the latest specs and browsers, supports more events than "readystatechange" (namely "error", "abort", "timeout", and "load"), and supports adding listeners using addEventListener rather than just setting the "onreadystatechange" property: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Events

It would be nice if web developers could have a polyfill that allows us to rely on the presence of these events and not worry about our code breaking on IE9.

keyboardevent.key fixing

hi, for firefox, the code seems to use the KeyboardEvent.key property if existing, but that one isn’t supported fully.

e.g. firefox uses (until version 37 lands) "Down" instead of "ArrowDown" etc.

[Quick] question

Can I use the polyfill with Modernizr? I'm a bit confused as to what it actually does compared to your polyfill. I believe it's gonna be like this: I only need CSS selectors and CSS3 support, so only the first tab, your polyfill would probably include the HTML, DOM, EVENTS parts.

I just decided to go Native JS, I read left and right and feel very scared+amazed there is freedom.. so I speak a bit n00b-ish, sorry.

Uncaught TypeError: Cannot convert a Symbol value to a string

es6.js, 259 line:
Uncaught TypeError: Cannot convert a Symbol value to a string
assert(symbolForKey(String(global.Symbol('x'))));

I have this error in Chrome 37.0.2054.3 dev (and 37.0.2062.3 dev).
I don't have this error in Firefox 33.0a1, iOS 7.1.1's Safari.
If I comment this line, I get the same error in another line.

I found that Chrome now provides its own (i.e. without polyfills) Symbol:
typeof Symbol === 'function' (it is 'undefined' in other browsers)
typeof Symbol('x') === 'symbol'
Symbol('x').toString() === 'Symbol(x)'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.