views:

54

answers:

1

I'm especially liking the ability to require other javascript classes by using Google Closure, but I'm wondering if it's possible to use goog.require to lazy load other javascript classes. When I trying using goog.require after the page has loaded, it seems to refresh or go blank :( Any way to get a script on demand, and maybe set it up with a callback, so I can run some javascript when it's done loading?

+1  A: 

goog.require is not designed to be used to load any script. However, there is nothing special in lazy-loading script files on demand. Simply create node dynamically and add it to your page:

function require(src)
{
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    document.body.appendChild(script);
}

The above function will load the script from the URL specified by the src parameter.

The callback is another story. You do not get an event fired after a script is loaded. If you want to get notified when the script has loaded, you need to notify of the loaded script from the script itself. For example, you can call a predefined function on your page as a last statement in the javascript file you are loading. Once this function is called, you know the script has finished loading. To do that, however, you need to be able to modify the loaded script file.

A similar approach for notifying a script has loaded is used with JSONP. The JSONP data is retrieved using the same approach above - you add a dynamically created script node to the page. However, by default, returning data from the server does not cause a change of state. A function call is needed to indicate something has happened (e.g. the data has arrived). With JSONP, you specify the name of a function in the URL of the JSONP request. The server then returns a piece of javascript where the function you specified is called, passing the JSON data in an argument.

All this is to suggest you need to be able to call a function on page after the script has loaded.

bugventure
appending script files isn't hard, but the beauty of goog.require (which does indeed trigger a script file to be included, when you're running your app before closure compilation) is that it figures out if that script file has already been included on the page, and doesn't download it again if it has. So you're not aware if this kind of thing already exists in closure? (as in, some convenience methods, etc).
chrismarx
I believe you could have the same principle implemented by caching the URLs of your script resources. If a script you want to retrieve has a cached URL, this means it has already been retrieved.
bugventure