Mustache template system

Hello,

This is my first script written using mustache.js external template system, the below code is executing fine in FF but showing some error in Chrome, does anyone faced these type of issue and may i know the reason.

“Uncaught TypeError: Cannot read property ‘innerHTML’ of null”

<!doctype html>
<html lang="en">
  <head>
    <title>Mustache.js External Method</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" ></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.1/mustache.js" ></script>
    <script>
      $(document).ready(function(){
        var view = {
          name : "Peter",
          occupation : "Web Developer"
        };

        $("#templates").load("template.html #template1",function(){
          var template = document.getElementById('template1').innerHTML;
          var output = Mustache.render(template, view);
          $("#person").html(output);
        });
      });
    </script>
  </head>
  <body>
    <p id="person"></p>
    <div id="templates" style="display: none;"></div>
  </body>
</html>
1 Like

If the page hasn’t loaded in when the script runs it can’t find any elements - they aren’t there to find yet - hence the NULL

Call in the libraries in the head, but putting the rest just before the closing body tag should solve most of your problems of this type.

1 Like

Hello Mittineague,

Thanks for quick response.

Good tip from you, but as one of the best practice I have changed the code structure bit i.e calling every script externally though I am getting the same error.

<!doctype html>
<html lang="en">
  <head>
    <title>Mustache.js External Method</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" ></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.1/mustache.js" ></script>
    <script src="script.js"></script>
      </head>
  <body>
   <p id="person"></p>
    <div id="templates" style="display: none;"></div>  
   </body>
</html>
1 Like

Put just this line immediately before the body closing tag and see what results you get.

1 Like

If you want to keep run scripts in the head, you’ll need to have them run on load / ready / complete

Much easier and perfectly acceptable to have them after the DOM has loaded in.

BTW, not sure what you’re doing, but you may want to not have display none there and use JavaScript to hide / then show it.
The way it is now, you risk some visitors never seeing it. .

1 Like

It also helps keep the search engines happier - they don’t like pages that waste time loading scripts before they load the page content and rank them much lower in their search results.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.