參考資料:document.ready和window.onload的區別
公司的項目是用html來寫的前端;
由於最近因爲業務擴展需要變更名字然後部署到不同的客戶,又不想更改爲jsp;
因此想了個辦法,就是定義一個js變量在頁面加載時讀取當前瀏覽器地址,切割出項目名;
直接將這個代碼塊放入一個js;
在每個頁面引入之後,直接使用publicField.projectName即可;
//定義一個對象
var publicField = {};
//定義對象中的屬性
publicField.projectName = "";
/**
* 自定義document.ready方法;
* 此方法執行在window.onload之前;
* @param callback
*/
document.ready = function (callback) {
///兼容FF,Google
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', function () {
document.removeEventListener('DOMContentLoaded', arguments.callee, false);
callback();
}, false)
}
//兼容IE
else if (document.attachEvent) {
document.attachEvent('onreadystatechange', function () {
if (document.readyState == "complete") {
document.detachEvent("onreadystatechange", arguments.callee);
callback();
}
})
}
else if (document.lastChild == document.body) {
callback();
}
}
//頁面加載之前執行;
document.ready(function () {
var href = window.location.href;
//頁面url通常爲http://localhost:8090/XXXX/images/1_15.png
//先切割//,得到
// http:,localhost:8090/XXXX/images/1_15.png
//取第二個,再切割/,得到
//localhost:8090,XXXX,images,1_15.png
//取第二個,得到項目名,XXXX然後重寫當前頁所有引入的url
//拼接/+項目名,得到/XXXX前綴,
publicField.projectName = "/"+href.split("//")[1].split("/")[1];
})