首页 文章

通过ScriptInjector注入jQuery

提问于
浏览
0

当试图通过ScriptInjector注入jQuery时,这是通过JSNI调用 $wnd.$ 时抛出的错误:

引起:com.google.gwt.core.client.JavaScriptException:(TypeError):对象[object global]在com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:)中没有方法'$': 248)com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)com.google.gwt com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid上的.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:289)(JavaScriptHost.java:107)

这是注入jQuery的代码:

ScriptInjector.fromUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js")
            .setWindow(ScriptInjector.TOP_WINDOW).setCallback(new Callback<Void, Exception>() {
                @Override
                public void onSuccess(Void arg0) {
                    GWT.log("Success to load jQuery library");
                    ScriptInjector.fromUrl("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js").setWindow(ScriptInjector.TOP_WINDOW).inject(); 
                }

                @Override
                public void onFailure(Exception arg0) {
                    GWT.log("Failed to load jQuery library");
                }
            }).inject();

可能是什么问题呢?

3 回答

  • 1

    使用 ScriptInjector.fromUrl() 加载外部javascript文件是异步执行的,因此可能是在加载jQuery之前尝试调用 $wnd.$ . 延迟通话或使用 onSuccess 继续您的应用的工作流程 .

    顺便说一句,如果你有兴趣在你的应用程序中使用jquery-ui,你可以看看Gwtquery-ui插件,它自动加载javascript依赖项,它不是一个纯gQuery插件,依赖于jQuery和jQuery-ui,但它与gwt和gQuery有很好的集成 .

    [EDITED]

    我最近添加到gQuery(1.4.0-SNAPSHOT)的一个新功能是JsniBundle,用于包含外部javascript作为JSNI块:

    public interface JQuery extends JsniBundle {
       @LibrarySource("http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js")
       // You can use javascript files placed in your source tree as well
       // @LibrarySource("jquery.js")
       public void load();
    }
    
    // Generate the Bundle implementation
    JQuery jQuery = GWT.create(JQuery.class);
    // Load the third-party library
    jQuery.load();
    

    使用 JsniBundle 的目标是:

    - Use pure javascript files so as we can use IDEs for editing, formating etc,
         instead of dealing with code in comment blocks.
       - Facilitate writing and testing javascript in the browser before compiling it.
       - Include third-party javascript libraries without modification of the original source.
       - Not need of adding javascript tags in the html page or module file to include
         third-party javascript.
       - GWT compiler will get rid of any jsni fragment if the application does not use it.
       - Included javascript will take advantage of GWT jsni validators, obfuscators
         and optimizers.
    
  • 4

    正确的语法是使用$ wnd.jQuery而不是$ wnd . $我认为它与gwt iframe中保留的$有关 .

  • 0

    尝试在成功回调中加载jquery代码段代码,也就是说,当jquery lib结束加载时 .

相关问题