neekfenwick::blog

Stuff that seemed important at the time.

Script Inject Dojo Into a Web Page

This is an example worked through by others on #dojo IRC channel on Freenode. It pushes a script tag to load dojo.js, and hooks onto the relevant load event to callback when the load is complete and it’s safe to invoke the symbols defined in the script.

Example Javascript example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function loadScript(url, callback) {

  var script = document.createElement("script")
  script.type = "text/javascript";

  if(script.readyState) {
      script.onreadystatechange = function() {
          if(script.readyState == "loaded" || script.readyState == "complete") {
              script.onreadystatechange = null;
              callback();
          }
      };
  } else {
      script.onload = function() {
          callback();
      };
  }

  script.src = url;
  document.getElementsByTagName("head")[0].appendChild(script);
}

window.onload = function() {
  loadScript("https://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js", function() {

      console.log("dojo.js has now loaded.  require, define etc. global symbols are now exported and ready for use. ");

      require(["dojo/dom", "dojo/fx", "dojo/domReady!"], function(dom, fx) {
          console.log("** use dojo here! **");
      });
  });
}

Credit: Pallet/James Masters