1

Here is my html.

<html>
  <head>
    <script src="closure-library/closure/goog/base.js"></script>
    <script src="hello.js"></script>
  </head>
  <body onload="sayHi()">
  </body>
</html>

And here is my hello.js file.

var options = {
    "style" : "background:#EEE;"
}

function sayHi() {
  goog.require("goog.dom");
  var header = goog.dom.createDom("h1", options, "hello world");
  goog.dom.appendChild(document.body, header);
}

Why does Chrome Console issue this error?

Uncaught TypeError: Cannot call method 'createDom' of undefined 

In general, I don't think I can require a library in the same code block in which I call a function from the library. I just saw this in the documentation, but I was wondering why.

4

1 回答 1

3

In uncompiled Closure code, each goog.require(NAMESPACE) results in a call to:

document.write('<script src="SCRIPT_PROVIDING_NAMESPACE"></script>');

The dependencies are defined with calls to goog.addDependency(relativePath, provides, requires) in deps files generated with depswriter.py. Using the Chrome Developer Tools, the Elements tab shows all of the <script> elements dynamically inserted based on the Closure Library dependencies defined in deps.js.

In your example, when sayHi() is triggered by the body onload event, a new <script> element is inserted in the header. However, this new <script> element has not yet loaded goog.dom. Therefore, goog.dom is undefined.

If you change hello.js as follows:

goog.require("goog.dom");

var options = {
    "style" : "background:#EEE;"
}

function sayHi() {
  var header = goog.dom.createDom("h1", options, "hello world");
  goog.dom.appendChild(document.body, header);
}

Then goog.require("goog.dom") gets executed prior to the onload event and the inserted <script> element has a chance to load dom.js prior to the call to sayHi().

于 2012-06-06T02:23:14.770 回答