Dojo FAQ: Should I use parseOnLoad or parser.parse()?

By on March 12, 2014 10:34 am

DojoFAQ

There are two ways to create widgets based on HTML declarations: by using the parseOnLoad property of dojoConfig and by manually calling dojo/parser‘s parse method. Developers often ask which to use and why. The purpose of this post is to answer that question.

Setting parseOnLoad to true tells Dojo to apply dojo/parser to the entire body after the page is loaded. This is simple and works well when the page contains mostly widgets and no setup logic is required after the parse. For example:

  <div data-dojo-type="dijit/form/Form"
    id="login-form" action="login.php" method="POST">
    <label for="username">Username</label>
    <input data-dojo-type="dijit/form/TextBox" id="username">
    <label for="password">Password</label>
    <input data-dojo-type="dijit/form/TextBox" id="password" type="password">
    <button data-dojo-type="dijit/form/Button" type="submit">Submit</button>
  </div>
  <script data-dojo-config="async: true, parseOnLoad: true" src="dojo/dojo.js"></script>

In practice, however, many applications require setup code to run after parsing is complete. Others have large, widget-free sections that are wasteful to parse. The following is an example of both. The subtree containing widgets is only a small part of the page, and setup logic must be executed after parsing is complete. The example uses parser.parse() to target just the DOM subtree containing the widgets and to execute setup logic afterward.

  <div class="sidebar">
    ...
    <div data-dojo-type="dijit/form/Form" id="login-form">
      <label for="username">Username</label>
      <input data-dojo-type="dijit/form/TextBox" id="username">
      <label for="password">Password</label>
      <input data-dojo-type="dijit/form/TextBox" id="password" type="password">
      <button data-dojo-type="dijit/form/Button"
        id="login-button" type="submit">Submit</button>
    </div>
    ...
  </div>
  <div class="main-content">...</div>
  <script data-dojo-config="async: true" src="dojo/dojo.js"></script>
  <script>
    require([
      'dojo/parser', 'dojo/dom', 'dojo/on', 'dojo/domReady!'
    ], function (parser, dom, on) {
      var formNode = dom.byId('login-form');
      parser.parse(formNode).then(function () {
        on('login-button', 'click', function () {
          // custom login code
        });
      });
    });
  </script>

Both parseOnLoad and parser.parse() have a role, but unless your application is a whole-page app with no post-parse setup required, parser.parse() is likely what you need.

Comments