Skip to content

Conditionally load polyfills in JavaScript

This tutorial shows you how to conditionally load polyfills in JavaScript, polyfills should only be loaded if they are needed. A polyfill that is loaded when not needed can make your code work less good or make it not work at all. is a great online service that enables you to conditionally load polyfills and to download the polyfills that you need. Calling an online service for polyfills is risky because the service can be unavailable temporarily or permanently.

Find and collect polyfills

You first need to know which polyfills you need, this depends on your code and the browers you want to support. You can find out which polyfills you need by testing your code in an older target browser. We need polyfills for: Element.prototype.closest, Array.from, Array.prototype.includes, window.CustomEvent, window.Promise, window.XMLHttpRequest, Element.prototype.remove, String.prototype.endsWith, String.prototype.includes and datalist.

You can search the Internet for these polyfills. Set flags to always and gated if you download from, this will give you the full polyfill with feature detection.


I have saved each polyfill that I found to a separate file and I store them in a folder. The code below shows the code to load script files if they are needed, it is important that files are loaded synchronous. The file with this code must be loaded before other scripts that depend on these scripts.

(function () {


    if (!Element.prototype.closest) {
    if (!Array.from) {
    if (!Array.prototype.includes) {
    if (typeof window.CustomEvent !== 'function') {
    if (!window.Promise) {
    if (!window.XMLHttpRequest) {
    if (!Element.prototype.remove) {
    if (!String.prototype.endsWith) {
    if (!String.prototype.includes) {
    if ('options' in document.createElement('datalist') === false) {

    // Load a script file synchronous
    function loadScript(src) {
        var js = document.createElement('script');
        js.src = src;
        js.async = false;

    } // End of the loadScript method


Leave a Reply

Your email address will not be published. Required fields are marked *