我正在尝试在来自网页的 img src=... 调用上实现即发即弃,并且正在寻找最可靠的方法。为什么?
在大多数 Web 跟踪系统(如 Omniture 或 Coremetrics)中,都会请求一个 img src,它也恰好携带了跟踪系统要记录的所有数据。与任何其他图像请求一样,页面会尝试等待响应,这可能会减慢页面加载速度。
我正在尝试做的是实现一个跟踪系统,其中网页响应时间比请求是否实际成功具有更高的优先级,因此在所有条件下等待响应都是完全没有必要的,包括......
- 服务器收到请求,并可以轻松响应(HTTP 响应代码 200)
- 服务器收到请求,但陷入困境,仍然可以轻松响应错误 500 响应代码
- 服务器根本没有运行
- 由于 DNS 故障,找不到服务器
- 请求到达了服务器,但被卡住了,需要很长的时间来响应。
我已经使用 XMLHttpResponse 对象和一个异步请求进行了调查,该对象可能会悄悄失败,但您很快就会遇到同源策略和浏览器兼容性代码膨胀。我相信一个简单的 jane img 请求仍然是最好的请求机制,但我正试图用最少的代码找出最好的即发即弃的实现。到目前为止,我知道我可以...
onerror="this.parentNode.removeChild(this)" onload="this.parentNode.removeChild(this)"
This works pretty well on scenarios 1 through 4 where there is a finite and predictable conclusion to the request. It breaks down in scenario 5, which could be avoided if there were something in-between.
I'm toying with the idea of seeing if this.src.readyState == "complete" but see that I am heading down a road of browser compatiblity and race-condition hell were it would be wise to tap the StackOverflow community first.
Anyone have experience with this and a good solution?