Reputation: 69
My objective is to call a method in java using JSNI and to make that call from a handwirtten javascript code, That is to say: I will have a function inside the $(document).ready
that will call a method in java.
My problem is that I don't know which script will be loaded first: the GWT script or my handwritten javascript script, And because of that I wonder if there is a solution to integrate $(document).ready
to be loaded after GWT has been loaded because if the GWT is loaded first the JSNI methods are not known yet by the javascrpit object window and an error is thrown.
Upvotes: 0
Views: 947
Reputation: 46841
A good way is to load your custom JavaScript
files after exporting all the required JSNI.
Try any one
Once all the JSNI
methods are exported then you can add your custom JavaScript
in the page using below JSNI
.
public static native void loadCustomJS() /*-{
var js = $doc.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
$doc.body.appendChild(js);
}-*/;
Create a JavaScript
function in your HTML/JSP and call it from Entry Point class once all the JSNI's are exported.
HTML/JSP
...
<script type="text/javascript">
function loadCustomJS(){
// load your custom JavaScript here
}
</script>
...
Entry Point Class:
public static native void loadCustomJS()
/*-{
$wnd.loadCustomJS();
}-*/;
Upvotes: 1
Reputation: 628
If you want to use a pure GWT solution, you can take advantage of GWT´s ScriptInjector:
ScriptInjector.fromUrl("http://example.com/foo.js").setCallback(
new Callback() {
public void onFailure(Exception reason) {
Window.alert("Script load failed.");
}
public void onSuccess(Void result) {
Window.alert("Script load success.");
}
}).inject();
So, inside of your gwt´s onModuleLoad()
method, you can place this snippet. In that way you do not need to write a single extra line of JS.
Upvotes: 1
Reputation: 328566
There is a simple way to make sure your script runs after everything else: Put it into a <script>
element that you add as the last thing in your <body>
element:
<html><head>...</head>
<body>...
<script>/* your code here */</script>
</body>
The browser must make guarantees about the order in which script
elements are executed: They are executed in the order in which they appear in the DOM (this is also true for remote scripts; in that case, the browser can download the code in the background but it won't touch the next <script>
element before it the download has finished).
Note that you don't need to use $(document).ready()
if you use this "trick": Since your script
element is the last one in the DOM, by definition, the DOM must be "ready" at the time it's processed.
Upvotes: 0