防止jQuery在Ajax调用后加载图像

时间:2019-05-20 04:26:24

标签: javascript jquery ajax performance

我有一个ajax调用,它从本地代理php文件请求html。该代理从外部服务器下载html并返回,其中html通过jQuery进行解析。

$.ajax({
    type: 'POST',
    url: 'proxy.php',
    data: {
        goal: 'get',
        url: url
    },
    success: function(page) {

        let p = $(page),
            h1 = p.find('h1');

        //some code

        //<-- problem begins

    },
    error: function(response) {
        console.error(response);
    }
});

执行完一些代码后,它会在浏览器控制台中引发很多404错误,同时尝试下载一些外部图像,这会导致较高的处理器负载。实际上,我根本不需要那些图像,我只需要纯HTML。

我已经尝试过这些方法来释放一些内存,但这没用:

p.remove();
p = undefined;

如何防止加载图像或在使用后删除变量?

1 个答案:

答案 0 :(得分:0)

经过几分钟的研究,我发现了这个solution并编写了用于清理和存储src属性的简单函数:

cleanAndStoreSrc: function(html) {

    let h = $(html);

    h.find('img').each(function (ind, el) {
        let t = $(this),
            src = t.attr('src');
        t
        .attr('src-reserved', src)
        .removeAttr('src');
    });

    return h;

}

如果将发布更有效或更优雅的解决方案,我将接受它作为答案。