title: How do you get the contextPath from JavaScript, the right way?
body: <p>Using a Java-based back-end (i.e., servlets and JSP), if I need the contextPath from JavaScript, what is the recommended pattern for doing that, any why?  I can think of a few possibilities.  Am I missing any?</p>
  
  <p><strong>1. Burn a SCRIPT tag into the page that sets it in some JavaScript variable</strong></p>
  
  <pre><code>&lt;script&gt;var ctx = "&lt;%=request.getContextPath()%&gt;"&lt;/script&gt;
  </code></pre>
  
  <p>This is accurate, but requires script execution when loading the page.</p>
  
  <p><strong>2. Set the contextPath in some hidden DOM element</strong></p>
  
  <pre><code>&lt;span id="ctx" style="display:none;"&gt;&lt;%=request.getContextPath()%&gt;&lt;/span&gt;
  </code></pre>
  
  <p>This is accurate, and doesn't require any script execution when loading the page.  But you do need a DOM query when need to access the contextPath.  The result of the DOM query can be cached if you care that much about performance.</p>
  
  <p><strong>3. Try to figure it out within JavaScript by examining <code>document.URL</code> or the BASE tag</strong></p>
  
  <pre><code>function() {
      var base = document.getElementsByTagName('base')[0];
      if (base &amp;&amp; base.href &amp;&amp; (base.href.length &gt; 0)) {
          base = base.href;
      } else {
          base = document.URL;
      }
      return base.substr(0,
          base.indexOf("/", base.indexOf("/", base.indexOf("//") + 2) + 1));
  };
  </code></pre>
  
  <p>This doesn't require any script execution when loading the page, and you can also cache the result if necessary.  But this only works if you know your context path is a single directory -- as opposed to the root directory (<code>/</code>) or the multiple directories down (<code>/mypath/iscomplicated/</code>).</p>
  
  <p><strong>Which way I'm leaning</strong></p>
  
  <p>I'm favoring the hidden DOM element, because it doesn't require JavaScript code execution at the load of the page.  Only when I need the contextPath, will I need to execute anything (in this case, run a DOM query).</p>