Search code examples
javascriptjquerygoogle-closuregoogle-closure-library

How to goog.require JQuery from CDN?


I am currently experimenting with different JavaScript module formats and loader and also wanted to try out Google Closure.

I've got the basic example working, but can't figure out how to use goog.require for an external library. Let's take JQuery from CDN, for example.

Right now I'm doing the following. In the HTML page:

<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>

And in the script:

goog.require("Greets");
goog.provide("Greets.MsgDivMessenger");

Greets.MsgDivMessenger = function() {};
Greets.MsgDivMessenger.prototype.sendMessage = function(message)
{
    $('#msg').text(message);
};

This works as the global $ is included via the <script .../> tag in the HTML page itself.

But what I'd like to do is to load JQuery via goog.require, without the <script .../> tag in the HTML page:

goog.require("Greets");
goog.require("$");
goog.provide("Greets.MsgDivMessenger");

Greets.MsgDivMessenger = function() {};
Greets.MsgDivMessenger.prototype.sendMessage = function(message)
{
    $('#msg').text(message);
};

I have tried adding JQuery CDN URL as dependency:

goog.addDependency('https://code.jquery.com/jquery-2.1.3.min.js', ['$'], []);

But this did not work, goog.require has tried to load .../closure/goog/https://code.jquery.com/jquery-2.1.3.min.js instead.

Yes, I know that I don't need JQuery for $('msg'), but the point is to manage modules (including external ones) with Google Closure.

How could I goog.require JQuery from CDN?


Solution

  • This isn't the intended use and there is no support for it. goog.provide/require is a dependency management scheme. A file that declares a "goog.provide", can be required by declaring it with a goog.require. For production use, the dependencies would be preloaded or bundled.

    Unless you want to hack Closure, your only option is to host it with your sources.