Last active
October 28, 2018 20:29
-
-
Save carolineartz/0377bba452236abcf2f57079b1d3479f to your computer and use it in GitHub Desktop.
// source https://jsbin.com/sufiboz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<h2>Polyfill.io "Holy grail" approach</h2> | |
<p id='result'>Polyfills are loading…</p> | |
<p>See the JavaScript tab for details. This approach:</p> | |
<ul> | |
<li>Uses feature detection in the browser</li> | |
<li>Does not make a request if no polyfills are required</li> | |
<li>Loads all polyfills in one file</li> | |
<li>is asynchronous</li> | |
</ul> | |
<h3>About feature detection in the browser</h3> | |
<p>Many people think that assessing browser capabilities by inspecting the user-agent identifier of the browser is a really bad idea. In fact, it's really OK, and literally all major websites do it.</p> | |
<p>Polyfill.io recommends using server-side feature detection for better performance and accuracy (detection is not always as straightforward as a simple <code>('thing' in OtherThing)</code>) but for people who still want to do feature detection client side, this demo proves that polyfill.io does support that.</p> | |
<script> | |
// Create a list of the features this browser needs. | |
// Beware of overly simplistic detects! | |
var features = []; | |
('Promise' in window) || features.push('Promise'); | |
('IntersectionObserver' in window) || features.push('IntersectionObserver'); | |
('after' in Element.prototype) || features.push('Element.prototype.after'); | |
// If any features need to be polyfilled, construct | |
// a script tag to load the polyfills and append it | |
// to the document | |
if (features.length) { | |
var s = document.createElement('script'); | |
s.src = 'https://polyfill.io/v2/polyfill.min.js?features=' + features.join(',') + '&flags=gated,always&callback=main'; | |
s.async = true; | |
document.head.appendChild(s); | |
} else { | |
// If no polyfills are required, invoke the app | |
// without delay | |
main(); | |
} | |
function main() { | |
document.querySelector('#result').innerHTML = 'Ready to rock.'; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment