title: Best way to execute js only on specific page
body: <p>I was wondering what would be the best way to execute a java-script code only on specific pages.</p>
  <p>Let's imagine we have a template-based web-site, rewrite rule for the content ist set, jquery available and it basically looks like this:</p>
  <pre><code>  &lt;!DOCTYPE html&gt;
    &lt;html&gt;
     &lt;head&gt;
      &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;
     &lt;/head&gt;
     &lt;body&gt;
      ...
      include $content;
      ..
     &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  <p>content 'info' contains a button, we want something to happen on click, content 'alert' should give us a message when you hover a text field.</p>
  <p><strong>What is the best way to trigger these actions, without running into an error, because the object is not found?</strong></p>
  <p><strong>Option one: using     <em>window.location.pathname</em></strong></p>
  <pre><code> $(document).ready(function() {
        if (window.location.pathname == '/info.php') {
            $(&quot;#button1&quot;).click(function(){
              //do something
            })
        }else if(window.location.pathname == '/alert.php'){
             $(&quot;#mytextfield&quot;).hover(){
               alert('message');
             }
      }
  </code></pre>
  <p><strong>Option two: checking if elements exist</strong></p>
  <pre><code>$(document).ready(function() {
    if ($(&quot;#button1&quot;).length &gt; 0) {
        $(&quot;#button1&quot;).click(function(){
          //do something
        })
    }else if ($(&quot;#mytextfield&quot;).length &gt; 0){
         $(&quot;#mytextfield&quot;).hover(){
           alert('message');
         }
  }
  </code></pre>
  <p><strong>Option three: include the script in the loaded template</strong></p>
  <pre><code>//stands for itself
  </code></pre>
  <p>Is there a better solution? Or do I have to get along with one of these solutions?</p>
  <p>Your experience, usage, or any links related to this topic are appreciated.</p>
  <p><strong>//EDIT:</strong></p>
  <p>I might have choosen a bad example, the actual code would be somethin like:</p>
  <pre><code>    mCanvas = $(&quot;#jsonCanvas&quot;);
      mMyPicture = new myPicture (mCanvas);
  </code></pre>
  <p>where the myPicture constructor get's the context of the canvas element, and throws an error, if mCanvas is undefined.</p>