Frage

I've got a Closure environment running fine in my development environment. In a new folder & file, however, it is not working.

For example, take this test script:

goog.require('goog.dom');
console.log(goog);
console.log(goog.dom);
goog.dom.getElement('logout').innerHTML = "Heck";

That's all, plus the base.js in the HTML.

The first console.log shows an object with all the right stuff is in there. All the files are loaded into the DOM too.

The second console log, however, says undefined and so the last line doesn't work (obviously). The Chrome console error is Uncaught TypeError: Cannot call method 'getElement' of undefined.

What the heck is going on? It's the same if I try XhrIo. It's not finding the methods on the goog object.

Thanks.

War es hilfreich?

Lösung

Documentation:

Note: Do not put your goog.require() statements in the same script tag as the entry point to code that uses the goog.required functions or classes. A goog.require() call adds code to the document after the script tag containing the call.

So

<script>
    goog.require('goog.dom');
    console.log(goog.dom);
</script>

prints undefined. But

<script>
    goog.require('goog.dom');
</script>
<script>
    console.log(goog.dom);
</script>

or

<script>
    goog.require('goog.dom');
    addEventListener('load', function() {
        console.log(goog.dom);
    });
</script>

prints an Object.

FYI, there are other possible workflows. For example, the closurebuilder.py script can help to load all the required files ahead of time.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top