0
votes

I've got a WebView. It's got some javascript. I need to dynamically and synchronously load more javascript stored in the assets folder.

eval() works just fine when I pull in the code from the asset by hand and pass it as a string.

The problem is that stack traces aren't useful for code that was pulled in with a string eval. You just get "eval at (file:///android_asset/..."

Is there another way to dynamically pull in javascript code, from javascript, that would make stack traces useful?

(FYI, I'm just using WebView as a javascript engine so I can use lots of our existing cross-platform javascript. It's not displaying any sort of useful HTML.)

Edit:

You can add this:

/@ sourceURL=snarkloading.js

To the string that gets evaled, and you'll get snarkloading.js as the name of the file.

1
Just embed it through your javascript as a new <script> element and the browser will properly add the new scripts. And no, don't fetch the contents, just use the src parameter and link to the .js file. - TheZ
Your answer is useful, but I edited and added a critical word - "synchronously". (And there's no UI here; no one cares if the code stalls waiting for IO for a second. That's fine.) - James Moore
I hope you realize that it won't just be the code that stalls, the whole page will be unresponsive. If that's okay, then synchronously will work. - TheZ
There is no UI, and there's no page to be unresponsive. We're using javascript as a regular programming language, not to manipulate UI elements. (OK, we're using a hidden WebView, so there is a page, but no one cares. If I could get a javascript engine without a UI, I'd do it.) - James Moore

1 Answers

2
votes

You can load scripts like this...

var script = document.createElement('script');
script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
script.onload = function () {
    // Do your thing when script is loaded
    alert('script loaded'); 
}; 
document.documentElement.appendChild(script);

Write your code in the onload event handler. This is when the code is actually downloaded and available.

Update There is a way to download scripts synchronously. I remember using the jQuery Ajax function for this with the following option.

async (Boolean)

Default: true

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false is deprecated.

You can read more about this on the jQuery API documentation for Ajax. The documentation states that it is deprecated in as jQuery 1.8. But if you can get your hands on an older version you can use that one or figure out how they did it.