How to control CSS and JavaScript load order
Learn how to declare dependencies between stylesheets and scripts so they load in the right order
Class ResourceReference allows to specify the resources it depends on overriding method getDependencies(). The method returns a list of HeaderItemS that must be rendered before the resource referenced by ResourceReference can be used. This can be really helpful when our resources are JavaScript or CSS libraries that in turn depend on other libraries.
For example we can use this method to ensure that a custom reference to JQueryUI library will find JQuery already loaded in the page:
Url jqueryuiUrl = Url.parse("https://ajax.googleapis.com/ajax/libs/jqueryui/" +
"1.10.2/jquery-ui.min.js");
UrlResourceReference jqueryuiRef = new UrlResourceReference(jqueryuiUrl){
@Override
public List<HeaderItem> getDependencies() {
Application application = Application.get();
ResourceReference jqueryRef = application.getJavaScriptLibrarySettings().
getJQueryReference();
return Arrays.asList(JavaScriptHeaderItem.forReference(jqueryRef));
}
};
Please note that in the code above we have built a resource reference using a URL to the desired library instead of a package resource holding the physical file.
[!NOTE] Wicket already provides base class org.apache.wicket.resource.JQueryPluginResourceReference for those JavaScript resources that depend on JQuery. This class uses the JQuery version bundled with Wicket.
[!NOTE] The same method getDependencies() is defined also for class HeaderItem.