0

I'm trying to lazy load javascript into the head with this function:

function bfLoadScripts(strPath) {
    var r = false;
    var scriptTag = document.createElement('script');
    scriptTag.src = strPath;
    scriptTag.type = 'text/javascript';

    scriptTag.addEventListener('load',function() {
        //alert('JS loaded');
            r = true;
    });
    var headTag = document.getElementsByTagName('head')[0];
    headTag.appendChild(scriptTag);
}

It works in FF (latest), Chrome (latest), IE 11 but not on Safari iOS 5.1 and Safari PC.

I tried this before but it's also not supported in Safari:

    scriptTag.onload = scriptTag.onreadystatechange = function() {
        if ( !r && (!this.readyState || this.readyState == 'complete') ) {
          r = true;
    };

Is there a polyfill for the "onload" event? Or asked differently: Is there a total different way of doing this? Without overloading the whole process by using libraries, plugins etc.

Matthias Max
  • 595
  • 1
  • 7
  • 20
  • 1
    See here: http://stackoverflow.com/questions/11160948/how-to-know-if-jquery-has-finished-loading/11161045#11161045 for a simple DIY version or http://microjs.com/#loader for lots of tiny/compact third party options. – jfriend00 Apr 13 '14 at 10:43
  • Brilliant, this is worth a penny! Thanks. – Matthias Max Apr 14 '14 at 08:09
  • IE 11 in "IE 8 mode" has script.readyState === "loaded" – 4esn0k Nov 05 '19 at 21:40

1 Answers1

0

This is my version, which works in IE 8 (TypeScript):

type IE8ScriptReadyState = "loading" | "loaded";

interface IE8CompatibleScriptElement extends HTMLScriptElement
{
    onreadystatechange: ()=> void;
    readyState: IE8ScriptReadyState;
}

export function loadPolyfill(src): Promise<void>
{
    return new Promise(function (resolve, reject)
    {
        let js = <IE8CompatibleScriptElement>document.createElement('script');
        js.src = src;

        if (!('onload' in js))
        {
            // @ts-ignore
            js.onreadystatechange = function ()
            {
                if (js.readyState === 'loaded')
                {
                    js.onreadystatechange = null;
                    resolve();
                };
            };
        }


        js.onload = function ()
        {
            js.onload = null;
            resolve();
        };

        js.onerror = function ()
        {
            js.onerror = null;
            reject(new Error('Failed to load script ' + src));
        };

        js.oncancel = function ()
        {
            js.oncancel = null;
            reject(new Error('Cancelled loading of script ' + src));
        };

        if (document.head)
            document.head.appendChild(js);
        else
            document.getElementsByTagName('head')[0].appendChild(js);            
    });
}

// loadScript("foo", function () { alert("hi"); });
// loadScript("/ts/myimport.js", function () { alert("hi"); });
function loadScript(src: string, done: (err?: Error) => void)
{
    console.log(src);

    let js = <IE8CompatibleScriptElement>document.createElement('script');
    js.src = src;


    if (!('onload' in js))
    {
        // @ts-ignore
        js.onreadystatechange = function ()
        {
            if (js.readyState === 'loaded')
            {
                js.onreadystatechange = null;
                if (done != null)
                    done();
            };
        };
    }


    js.onload = function ()
    {
        js.onload = null;
        console.log("onload " + src);
        if(done != null)
            done();
    };

    js.onerror = function ()
    {
        js.onerror = null;
        console.log("onerror " + src);

        if (done != null)
            done(new Error('Failed to load script ' + src));
    };


    //js.onloadend = function ()
    //{
    //    alert("onerror");
    //    done(new Error('Failed to load script ' + src));
    //};


    js.oncancel = function ()
    {
        js.oncancel = null;
        console.log("oncancel " + src);
        if (done != null)
            done(new Error('Cancelled loading of script ' + src));
    };

    if (document.head)
        document.head.appendChild(js);
    else
        document.getElementsByTagName('head')[0].appendChild(js);
}
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442