The introduction here is essentially two methods, by creating a DOM or computing through JavaScript:
1) Through the newly created Image, an Aborted request will be sent after testing, and IE6 does not support it. The same is true for changing the new Image to document.createElement('IMG'); the test should not like this solution;
The code copy is as follows:
function getAbsoluteUrl(url){
var img = new Image();
img.src = url; // Set the relative path to Image, and a request will be sent at this time
url = img.src; // At this time, the relative path has become an absolute path
img.src = null; // Cancel the request
return url;
}
getAbsoluteUrl("showroom/list");
2) Create an Anchor (link). This method will not make any requests (the request will be generated when joining the DOM), but IE6 does not support it.
The code copy is as follows:
/*jslint regexp: true, white: true, maxerr: 50, indent: 2 */
function parseURI(url) {
var m = String(url).replace(/^/s+|/s+$/g, '').match(/^([^://?#]+:)?(////(?: [^:@]*(?::[^:@]*)?@)?(([^://?#]*)(?::(/d*))?))?([^ ?#]*)(/?[^#]*)?(#[/s/S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
}
function absoluteURI(base, href) {// RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(/./.?(//|$))+/, '')
.replace(///(/.(//|$))+/g, '/')
.replace(////./.$/, '/../')
.replace(///?[^//]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^///, input.charAt(0) === '/' ? '/' : '');
}
href = parseURI(href || '');
base = parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.p athname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
}
Because our products are mobile web pages, they no longer support IE6, and the second solution is finally used;
It can be seen that when accessing all Image and Anchors using the original method, the returned absolute paths are all. At this time, if you want to return the original relative path, you can use the method of querying the DOM, such as the jQuery.attr() method:
The code copy is as follows:
//Return the absolute path, the jQuery object is essentially a "class array" structure (similar to arguments), so you can use [0] to access the original object and then take "href";
console.log($anchor[0]["href"]);
//Return to the original path
console.log($anchor.attr("href"));