在看LABjs源代碼時(shí),發(fā)現(xiàn)里面有個(gè)將相對地址轉(zhuǎn)為絕對地址的函數(shù),將其拿出紀(jì)錄如下:
function canonical_uri(src, base_path)
{
var root_page = /^[^?#]*///.exec(location.href)[0],
root_domain = /^/w+/://////?[^//]+/.exec(root_page)[0],
absolute_regex = /^/w+/://///;
// is `src` is protocol-relative (begins with // or ///), prepend protocol
if (/^//////?/.test(src))
{
src = location.protocol + src;
}
// is `src` page-relative? (not an absolute URL, and not a domain-relative path, beginning with /)
else if (!absolute_regex.test(src) && src.charAt(0) != "/")
{
// prepend `base_path`, if any
src = (base_path || "") + src;
}
// make sure to return `src` as absolute
return absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src);
}
如當(dāng)前頁面地址為:http://www.inspurstb.com/hzt/index.html
則canonical_uri("scy.js")返回http://www.inspurstb.com/hzt/scy.js
用Javascript將相對路徑地址,轉(zhuǎn)換為絕對路徑
1)使用Image, 經(jīng)測試會(huì)發(fā)送一個(gè)Aborted的請求,并且IE6不支持, 將new Image改成document.createElement_x_x_x('IMG')也是一樣的;測試應(yīng)該不喜歡這個(gè)方案;
function getAbsoluteUrl(url){
var img = new Image();
img.src = url; // 設(shè)置相對路徑給Image, 此時(shí)會(huì)發(fā)送出請求
url = img.src; // 此時(shí)相對路徑已經(jīng)變成絕對路徑
img.src = null; // 取消請求
return url;
}
getAbsoluteUrl("showroom/list");
2)使用Anchor(鏈接),不會(huì)發(fā)出任何請求,只會(huì)在加入DOM時(shí)產(chǎn)生請求,但是IE6也不支持
function getAbsoluteUrl(url){
var a = document.createElement_x_x_x('A');
a.href = url; // 設(shè)置相對路徑給Image, 此時(shí)會(huì)發(fā)送出請求
url = a.href; // 此時(shí)相對路徑已經(jīng)變成絕對路徑
return url;
}
getAbsoluteUrl("showroom/list");
3)使用JavaScript: 實(shí)現(xiàn)起來比較復(fù)雜,這里有一個(gè)例子: https://gist.github.com/1088850
最終使用的是option 2,
由此可變,用原生態(tài)的方法訪問所有的Image, Anchor時(shí),返回的都是絕對路徑,此時(shí)如果想返回原來的相對路徑,可以用查詢DOM的方法,如jQuery的.attr()方法:
console.log($anchor[0]["href"]); //返回絕對路徑,jQuery對象實(shí)質(zhì)上都是數(shù)組,即使只有一個(gè),因此使用[0]可以訪問到原生態(tài)的對象,然后取"href";
console.log($anchor.attr("href")); //返回原始路徑