Question

Should the RequireJS script tag be located in the <head> or bottom of an HTML page?

<script data-main="resources/js/main" src="require.js"></script>

I have seen reputable sources place the RequireJS script tag in either position, but no reputable source seems to explicitly say where the ideal location is.

Arguments for placing the tag in the head would be that RequireJS could already begin loading and executing dependent scripts asynchronously while the page continues loading (though this gain may be minuscule).

Arguments for placing the tag at the bottom of the page would be that checks for the DOM being ready wouldn't be needed within modules (though not including this check may cause problems if the module is used in a third-party system that loads the script in the <head> tag).

Was it helpful?

Solution

General best practice is to always place your script at the bottom.

You may have seen people including it in the HEAD as it is not doing a big difference.

I'd recommend in the bottom, because as you'll want to build your scripts before production, you'll end up loading all your script in the head otherwise.

Note that if you're running a "single page application", then it really doesn't matter as chances are your body will be empty - or almost empty.

OTHER TIPS

Put it at the bottom of the page, it's better for performance and if you're planning to manipulate the page (as expected) then you want it to load the page first anyway.

Best practice, with few exceptions, is always:

  • Load styles (css)
  • Load structure (html)
  • Load scripts (functionality)

I'm working on a project with a lot of templates and about 1MB of js on page load, and putting requireJS at the top of the page has it's perks. Require can start scheduling and parsing js while the rest of the html downloads. Also, we have noticed that, this allows us to 'require' css in the page before all of the html comes down.

I did find one caveat today, where script tags might execute twice if require is loaded in the page at the head/ before the script tag. I'm trying to create an example to debug.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top