It sounds like _spPageContextInfo gets added by SPWebPartManager which in turn gets added by default on majority of master pages. Since _spPageContextInfo object is already available on majority of SharePoint pages, you can just make following call sand it would return current site collection and sub site URLs.
For Site Collection URL => var url = window.location.protocol + “//” + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
For Sub Site URL => var url = _spPageContextInfo.webAbsoluteUrl;
This has saved at least few hours for me and probably will save lot many hours in future as a reference. Nice trick to have in your bag as we are building lots of client side code blocks in SharePoint.