Before we jump into the high weeds, I want to make everyone aware of the
_spPageContextInfo object that is initialized in every SharePoint page. Sahil Malik wrote a post entitled _spPageContextInfo is your new best friend and Marc D. Anderson wrote another article referencing Sahil’s entitled Using _spPageContextInfo to Determine the Current SharePoint Context in Script.
The _spPageContextInfo object. Learn it. Live it. Love it.