JavaScript Best Practices: where should I include my JavaScript?
<p>I am building a website using PHP and JavaScript, and I feel that I have a good grasp on where to include my JavaScript, but a more specific situation has come up that has me confused.  I currently have all of my JavaScript in one external file, which is being included on every PHP page.</p>

<p>Let's say that I have a paragraph with an id='myParagraph' and I need to highlight this paragraph in red with JavaScript on page load.  This paragraph is only on ONE PHP page and my website has about 50 different pages.  I immediately assumed that I should throw some code into my one external JavaScript file, something like:</p>

<pre><code>$('#myParagraph').css('color', 'red')
</code></pre>

<p>and the paragraph would be highlighted when that page loads.</p>

<p>My question is: is this the best way to do it?  To my understanding, every time I load a page it will be searched for an element with the id myParagraph, yet 98% of my pages won't even have that id.  Is this wasteful?  Should I instead include the following code:</p>

<pre><code>function highlightParagraph()
{
    $('#myParagraph').css('color', 'red')
}
</code></pre>

<p>in my one JavaScript file and then put some inline JavaScript in the PHP file with the id myParagraph to call the function highlightParagraph() when it's loaded?  That way, only the one page with myParagraph will be searched and highlighted.</p>

<p>I feel like option 2 is the best, but I read all the time not to use inline JavaScript.</p>

<p>edit: I realize that for this example you would just use CSS.  I'm just using it to get my question across</p>
