UIWebView stringByEvaluatingJavaScriptFromString in background

前端 未结 4 1444
温柔的废话
温柔的废话 2021-02-10 01:29

In an iOS app, I\'m running a fairly large script on a UIWebView using stringByEvaluatingJavaScriptFromString (large in terms of the length of the java

4条回答
  •  感动是毒
    2021-02-10 02:12

    No, Webviews and the Webkit JavaScript engine are both single-threaded and cannot be used on a background thread.

    A better option is to split up your JavaScript into discrete execution blocks and pipeline them using a JavaScript timer, like this (JS code, not Obj-C):

    var i = 0;
    var operation = function() {
    
        switch (i) {
        case 0:
           //do first part of code
           break;
        case 1:
           //do second part of code
           break;
        case 2:
           //do third part of code
           break;
        etc...
        }
    
        //prepare to execute next block
        i++;
        if (i < TOTAL_PARTS) {
            setTimeout(operation, 0);
        }
    };
    operation();
    

    That will prevent your script from blocking user interaction while it executes

提交回复
热议问题