开发者

Expand partial URL into full (like in image.src)

I'm trying to write an onerror handler for images that replaces them with a loading image and then periodically tries to reload them. The problem I'm having is that if the loading image fails to load, it goes into an infinite loop of failure. I'm trying to deal with this by checking if the URL is the loading image:

if(photo.src != loadingImage) {
    // Try to reload the image
}

Unfortunately, loadingImage can be a relative URL (/images/loadingImage.jpg), but photo.src is always a full URL (http://example.com/images/loadingImage.jpg). Is there any way to generate this full URL without passing the function any more information? Obviously I could pass it the host name, or require full URLs, bu开发者_StackOverflow社区t I'd like to keep this function's interface as simple as possible.

EDIT:

Basically what I want is to guarantee that if I do photo.src = loadingImage, that this will be true: photo.src === loadingImage. The constraint is that I know nothing about loadingImage except that it's a valid URL (it could be absolute, relative to the server, or relative to the current page). photo.src can be any (absolute) URL, so not necessarily on the same domain as loadingImage.


Here's a couple methods people have used to convert relative URLs to absolute ones in javascript:

  • StackOverflow - Getting an absolute URL from a relative one
  • Debuggable.com - Relative URLs in Javascript

Alternatively, have you considered doing the opposite - converting the absolute URL to a relative one? If loadingimage always contains the entire path section of the URL, then something like this would probably work:

var relativePhotoSrc = photo.src;
if (relativePhotoSrc.indexOf("/") > 0 && relativePhotoSrc.indexOf("http://") == 0) {
    relativePhotoSrc = relativePhotoSrc.replace("http://", "");
    relativePhotoSrc = relativePhotoSrc.substring(relativePhotoSrc.indexOf("/"), relativePhotoSrc.length);
}
alert(relativePhotoSrc);
if (relativePhotoSrc != loadingImage && photo.src != loadingImage) {
    // Try to reload the image
}

There's probably a slightly more efficient/reliable way to do the string manipulation with a regular expression, but this seems to get the job done in my tests.


How about this? The photo should either be a full URL or relative to the current document.

var url;
// There probably other conditions to add here to make this bullet proof
if (photo.src.indexOf("http://") == 0 || 
    photo.src.indexOf("https://") == 0 || 
    photo.src.indexOf("//") == 0) {
  url = photo.src;
} else {
  url = location.href.substring(0, location.href.lastIndexOf('/')) + "/" + photo.src;
}


Just check if they end with the same string:

var u1 = '/images/loadingImage.jpg';
var u2 = 'http://example.com/images/loadingImage.jpg'

var len = Math.min(u1.length, u2.length);
var eq = u1.substring(u1.length - len) == u2.substring(u2.length - len);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜