简体   繁体   English

用于加载脚本标签的 Polyfill<head>

[英]Polyfill for onload of script tag in <head>

I'm trying to lazy load javascript into the head with this function:我正在尝试使用此功能将 javascript 延迟加载到头部:

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.它适用于 FF(最新)、Chrome(最新)、IE 11,但不适用于 Safari iOS 5.1 和 Safari PC。

I tried this before but it's also not supported in Safari:我之前尝试过,但 Safari 也不支持它:

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

Is there a polyfill for the "onload" event? “onload”事件是否有polyfill? Or asked differently: Is there a total different way of doing this?或者换一种方式问:是否有完全不同的方式来做到这一点? Without overloading the whole process by using libraries, plugins etc.无需通过使用库、插件等重载整个过程。

This is my version, which works in IE 8 (TypeScript):这是我的版本,适用于 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM