Search code examples
javascriptjquery-selectorsdojoamdsizzle

Use of dojo/select on non-AMD code


I have on my site legacy JavaScript that uses Sizzle as selector engine.

I recently added the dojo library (v 1.8) for visualization purposes (charts, etc.). Because dojo includes selectors (dojo/select), I am thinking that Sizzle is now redundant and that I could replace it with dojo/select. Is there a way to make dojo/select work with non-AMD code?


Solution

  • Brandon Boone's answer is very useful so you do not have to rewrite your selector strings. I think what you are asking for is how to export dojo/query into global namespace, i.e. into window object through asynchronous nature of AMD. There are two options:

    1. If you use release version, it has dojo/query already packed in dojo.js, so you do not have to take care of asynchronous execution of module factory function, just export the variable:

      <script 
          src="http://ajax.googleapis.com/ajax/libs/dojo/1.8.0/dojo/dojo.js"
          data-dojo-config="async:true"
      ></script>
      
      <script>
          // export query module to global namespace (window object)
          require(["dojo/query"], function(query) {
              window.query = query;        
          });
      </script>
      
      <script>
          // query function is now available globally
          console.log(query("li"));
      </script>
      

      See this example in action at jsFiddle: http://jsfiddle.net/phusick/gvnGu/

    2. If you use baseless dojo, it would be more tricky because you actually have to wait for dojo/query to load:

      <script src="dtk-sdk/dojo/dojo.js" data-dojo-config="async:true"></script>
      
      <script>
          // wrap your lecacy code into a function so it's not executed immediately
          var executeNonAmdCode = function() {
              console.log(query("li"));
          }
      </script>
      
      <script>
          require(["dojo/query"], function(query) {
              // export query module to global namespace (window object)
              window.query = query;
              // execute the legacy code
              executeNonAmdCode();
          });
      </script>