prevent图像加载非DOM jQuery的AJAX解析 [英] Prevent images from loading on non-DOM jQuery AJAX parse

查看:114
本文介绍了prevent图像加载非DOM jQuery的AJAX解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery Ajax请求抓住和二级页面解析HTML .. 看着两个Chrome和FF的网络小组,我注意到,它会从那里加载图像,太 - 但只有当我加载在'成功'回调使用$(的数据)

I'm using jQuery ajax request to grab and parse HTML on a secondary page.. Looking at the Network panel of both Chrome and FF, I noticed that it will load the images from there, too -- but only when I load the result using $(data) in the 'success' callback.

的内容不会被装载到当前页面的DOM,所以我真的样的困惑,为什么这甚至发生。

The content is NOT loaded into the current page's DOM, so I'm really kind of confused why this is even happening.

但在任何情况下,简单地问,有没有办法来prevent这种情况的发生?我需要从结果抓取信息,但它从来没有击中的主要DOM。将脚本prevent图像加载到这里来看的工作,或将永远不会触发对加载的元素?请注意,这是一个userscript的应用程序,所以我不太有超过目标HTML控件。

But in any case, simply asked, is there a way to prevent this from happening? I need to grab information from the result, but it never hits the main DOM. Will scripts that prevent image loading until view work here, or would that never fire against the loaded element? Note this is for a userscript app, so I don't quite have control over the target HTML.

感谢您!

推荐答案

原因的为什么的这种情况正在发生的是,只要你创建一个 SRC 属性,即图像加载。例如:

The reason why this is happening is that as soon as you create an image with a src property, that image is loaded. For instance:

var image = document.createElement('img');
image.src = 'example.png';

图片是立即的由浏览器装载,然后将其添加到DOM。这实际上是通常的优化。例如,它可以用来将在后面所用preLOAD图像。

The image is immediately loaded by the browser, before it is appended to the DOM. This is actually generally an optimisation. For instance, it can be used to preload images that will be used later on.

由于jQuery的构建HTML字符串转换成DOM结构,它创建 IMG 的多为上面的片段做同样的方式元素。当图像元素开始存在,甚至在它被添加到DOM,该文件被从服务器装载

Since jQuery builds the HTML string into a DOM structure, it creates img elements in much the same way as the above snippet does. When the image element comes into existence, even before it is appended to the DOM, the file is loaded from the server.

最简单的解决方法是删除所有 IMG 标记从HTML您将追加前:

The simplest solution would be to remove all img tags from the HTML before you append it:

html = html.replace(/<img\b[^>]*>/ig, '');

如果这不是一种选择,你需要的 IMG 元素,你可以重命名的src 属性别的东西,或删除的属性,如果你不需要它们。

If that isn't an option and you need the img elements, you could rename the src attributes to something else, or remove the attributes if you don't need them.

这篇关于prevent图像加载非DOM jQuery的AJAX解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆