Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only running javascript required for current page, best methods?

So I know it's best to have one javascript file for an entire site to limit http requests. So obviously only some javascript is required for some pages. What is the best way of only running the javascript required for the current page?

EG.

if(page=='home'){
  //run javascript require for the home page
}

Maybe this isn't an issue and if targeting elements are not found on the page javascript will just fail gracefully? I would just like to know the best practice for this javascript structure.

like image 819
wilsonpage Avatar asked Feb 25 '23 02:02

wilsonpage


1 Answers

Encapsulate your logic in functions. Then just call the function(s) you need in each page, either via "onload" or an embedded function call in the page:

<script type="text/javascript">
   yourFunctionForThisPage();
</script>

Edit: Just to clarify: my answer is assuming the (implied) constraint of a single .js file. As others have pointed out, although you save on HTTP requests, this is not necessarily a good idea: the browser still has to parse all the code in the file for each page, whether used or not. To be honest it's pretty unusual to have a global site-wide js resource with everything in it. It's probably a much better idea to logically split out your js into various files, i.e libraries. These libraries could be page-based - i.e specific code for a particular page, or algorithm/task-based that you can include in whatever pages need them.

like image 103
Richard H Avatar answered Feb 26 '23 15:02

Richard H