Javascript – Is it still relevant to keep script tags in the footer

javascript

Working at a company that loads all javascript at the end of the page load. This means I can't do $(document).ready() on my page, because jquery isn't loaded (the scripts are injected into the footer by some template or other). I'm stumped on how to address this. I have one page where I want to run a function that is in a script, but the script is loaded last. If I make a case for moving the script(s) into the <head> I will need to make a compelling argument for it.

I've looked at the current code and every page runs a bunch of methods after the scripts are declared in the footer, which each check that they're on the relevant page and if so they execute. So it will run for example formatSearchResults() which checks to see if we're on the SearchResults page and if so will do some javascript, renderLoginPage(), setupProfilePage() etc. etc. Repeat this one by one for every page that requires javascript in the solution. This seems like a bad idea to me.

Historically I can maybe understand why, because downloading tons of scripts blocks the page loading. But these days I cannot understand why this is an issue.

  • Scripts are tiny and load very fast.
  • Once the script is loaded, it doesn't download it again (unless it changes) as the server simply asks the webserver if the file has changed.
  • Complex javascript libraries for manipulating the page like JQuery etc. did not exist back then.
  • Pages are much more complex these days and javascript is generally used in rendering and styling the page, rather than being something that adds behind the scenes magic at the end.

If I have to put calls to run my desired code in the footer, possibly via some complex callback mechanism then really the scripts aren't being loaded in the footer at all and I just have two bodies.

I wonder if anyone could shed some light on this, and explain if I am misguided, missing something, if there's more to it, etc.

Best Answer

You could always use the javascript pure equivalent of $(document).ready(function(){}) which is document.addEventListener('DOMContentLoaded', function() {}). This way you don't have to put the scripts in the head section of the page.

Running functions for every page even if its not relevent on that page is not a good practice and maybe you should think about separating those and loading every specific function on the related page.

Related Topic