Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Best Practices: where should I include my JavaScript?

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.

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:

$('#myParagraph').css('color', 'red')

and the paragraph would be highlighted when that page loads.

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:

function highlightParagraph()
{
    $('#myParagraph').css('color', 'red')
}

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.

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

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

like image 778
NZHammer Avatar asked Jul 04 '26 04:07

NZHammer


1 Answers

You should have a one "big" js file with the infrastructure functions and all the pages should have a reference to it.

Then each page should reference another js file with the functions related only.
The good things about using external js files are:

  1. The files are cached after the first download => Faster surfing.
  2. Separate of concerns, you keep the presentation tier away from the scripting tier.

Another important note:
The best way to change css is with css... not javascript. I

If you change the element style on DOM ready, just add the element definition

#myParagraph{color: red;}
like image 160
gdoron is supporting Monica Avatar answered Jul 06 '26 19:07

gdoron is supporting Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!