Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript and jQuery file structure

I have created a sizable application javascript and jQuery. However my file structure is getting a bit messy!

At the moment I have one large JS file with a if ($('#myDiv').length > 0) { test at the top to only execute the code on the correct page, is this good practice?

There is also a mixture of plain JS functions and jQuery extensions in the same file e.g $.fn.myFunction = function(e) {.

I also have a few bits of code that look like this:

function Product() {
  this.sku = '';
  this.name = '';
  this.price = '';
}
var myProduct = new Product;

Basket = new Object;

My question is for pointers on good practice regarding javascript and jQuery projects.

like image 226
Alan Whitelaw Avatar asked Apr 22 '26 09:04

Alan Whitelaw


1 Answers

The code if ($('#myDiv').length > 0) { is not good practice. Instead, make your page specific JS as functions and execute them in the corresponding page . Like this:

var T01 = function(){
  // JS specific to Template 01
};
var T02 = function(){
  // JS specific to Template 02
};

HTML head of Template 01:

<script type="text/javascript"> $(T01); </script>
like image 95
Simeon Avatar answered Apr 24 '26 00:04

Simeon



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!