1

I have created several JavaScript files, that all have to rely on jQuery, and therefore must be loaded after. This means (or I think so) that they all have to be included in the layout, meaning that they will load on every page the user tries to visit.

I was wondering if checking the path was the "best" way to limit the pages the script actually run on.

I am using something like this at the moment;

if(path)
{
   run code 
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Atle Kristiansen
  • 707
  • 7
  • 28
  • 2
    Don't add it at all? `they all have to be included in the layout` no, not necessarily. – Jonas Wilms Mar 05 '19 at 21:03
  • Is not the JavaScript files supposed to included at the end of the HTML? If that is the case (I thought that was best practice) this gives me two options, to include jQuery at each file, that needs them and then include that specific file or include them all once in the layout file, and then include some checks for running criterium. – Atle Kristiansen Mar 05 '19 at 21:11

1 Answers1

0

Add only those JS files to the layout page which are common for all(most) pages. JS files that are specific to a page should be included in that page only.

Rohit Shetty
  • 494
  • 3
  • 8
  • but what about the order of things? Should I include jQuery at both places? The bottom of the layout page is loaded after the content of the HTML. – Atle Kristiansen Mar 05 '19 at 21:13
  • JQuery should be loaded only once so add it to the layout page. – Rohit Shetty Mar 05 '19 at 21:15
  • Should I add it to the top of my layout page then/before the content loading? – Atle Kristiansen Mar 05 '19 at 21:46
  • it's best to place all your script references at the end of the page, just before

    .

    – Rohit Shetty Mar 05 '19 at 22:24
  • yea, that is what I thought. This results in the problem that I mentioned. jQuery has to be loaded before the scripts that depend on it, meaning that jQuery cannot be included in the layout if the other pages should have "local" imports. The layout has the body, and then for each page the content within the body varies, meaning that the individual pages don't (without the layout) have a body. – Atle Kristiansen Mar 05 '19 at 22:30