且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在AJAX请求上加载脚本?

更新时间:2023-12-05 08:17:10

你还没有证明你是怎样的加载HTML - 实际上你根本没有显示任何代码

You haven't shown how you are loading the HTML - in fact you've shown no code at all

但是,如果你的AJAX将HTML作为字符串获取,你可以使用以下

However, if your AJAX is getting the HTML as a string, you can use the following

const loadHtml = (text, dest) => {
    const p = new DOMParser();
    const doc = p.parseFromString(text, 'text/html');
    const frag = document.createDocumentFragment();
    while (doc.body.firstChild) {
        frag.appendChild(doc.body.firstChild);
    }
    const ret = Promise.all([].map.call(frag.querySelectorAll('script'), script =>
        new Promise(res => {
            const scriptParent = script.parentNode || frag;
            const newScript = document.createElement('script');
            if (script.src) {
                newScript.addEventListener('load', e => {
                    res({src:script.src, loaded: true});
                });
                newScript.addEventListener('error', e => {
                    res({src:script.src, loaded:false});
                });
                newScript.src = script.src;
            } else {
                newScript.textContent = script.textContent;
                res({src:false, loaded:true});
            }
            scriptParent.replaceChild(newScript, script);
        })
    ));
    dest = document.querySelector(dest);
    if (replace) {
        dest.innerHTML = '';
    }
    dest.appendChild(frag);
    return ret;
};

用法

let yourHTMLtext = '....'; // this would be the result of your AJAX call
loadHTML(yourHTMLtext, '#ajaxContent').then(results => {
    // at this point, all scripts have been loaded, if that's something you need to know
});