The main issue is that CRM Online uses the IFD configuration, which produces a URL like this:
https://<orgname>.crm.dynamics.com
But On-Premise (without IFD) uses a URL that looks like this:
http://<servername>/<orgname>/...
The easiest way to fix your problem is probably to configure IFD on your On-Premise install so you will get a URL that looks like CRM Online. Then your environments will match and your first line of code should work on both.
Configuring IFD is not for the faint of heart, so another option (although somewhat ugly) would be to add a condition to your javascript that looks for "crm.dynamics.com" in the LocalServerHost variable. If it is there, use the Online URL format, otherwise use the On-Premise URL format.