JavaScript, Handlebars, and OnLoad functions

I am using Handlebars in a Node/Express project. It works beautifully and its layouts, templates, and partials are a blessing. I have one question, though:

Where would the best place to place to put my JavaScript files import be?

This is the default layout I am currently using…

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="css/styles.css">
  <title>{{title}}</title>
</head>
<body>

  {{{ body }}}

  <script src="https://cdn.net/blahblahblah/jquery.min.js"></script>
  <script src="https://cdn.net/blahblahblah/bootstrap.min.js"></script>
  <script src="js/scripts.js" charset="utf-8"></script>
</body>
</html>

For those who may not know, Handlebars will insert my templates where the {{{ body }}} instruction is, which means I can focus on separate templates for different pages without bothering to repeat the same common structure(s).

As is, I get a NotDefined error when I try to run a JS function from the template when it loads. That makes sense since the template loads before the layout has a chance to load my scripts.js (last one to be loaded).

I can place the script loading statements inside the template, but that defeats the purpose of using templates as I would be duplicating code.

And, if I place the script loading statements early in the layout file, say within the head tag or immediately after opening the body tag, I fear I will have problems with performance.

So, where do you guys put your script loading statements in this situation?

If you have scripts in {{{body}}} that depend on the scripts lower in the page, then you either have to defer the running of the injected scripts (e.g. in document onload or equiv) or include your other scripts before {{{body}}}

1 Like

Yes… I was wondering if there was a different way to tackle the problem using Handlebars. :frowning: Thanks for taking the time to reply, though. :slight_smile:

Unfortunately, no. This is a minor hassle of scripts that deal with layout and content. You have to run them ahead of everything else that your page might need for displaying itself. There will be a performance impact, but it won’t be too bad since handlebars is fairly small and optimized. You should ensure any non-templating code runs after page load.

1 Like