How to speed up loading when more than one webviews load html in a FlatList using Native UI Components

I have been playing around with native ui components and integrating them into a React Native App.

What I’m trying to do is create a messaging system within my app so users can send a message and reply to messages, but the way I want the messages to be displayed is using WebView’s because I want to show links and iframes in the WebView or the message item. I was using simply a Text Component which works well but cannot display links and iframes of YouTube videos in the component.

So I went and developed a Native UI Component that has a WebView in a linear layout and returning this Native Ui Component using View Manager, ReactPackage, JavaScript Interface and the Custom View that returns the Linear Layout that contains the WebView.

This is my View MAnager:

    package com.poller;

    import android.graphics.Color;
    import android.view.ViewGroup.LayoutParams;
    import android.text.Html;
    import android.widget.TextView;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.LinearLayout;
    import android.opengl.GLSurfaceView;
    import android.widget.Toast;

    import androidx.annotation.Nullable;

    import com.facebook.react.common.MapBuilder;
    import com.facebook.react.uimanager.SimpleViewManager;
    import com.facebook.react.uimanager.ThemedReactContext;
    import com.facebook.react.uimanager.annotations.ReactProp;
    import com.facebook.react.views.text.ReactTextShadowNode;
    import java.util.Map;
    import java.util.UUID;

    public class MyCustomViewManager extends SimpleViewManager<CustomView> {

        public static final String REACT_CLASS = "MyCustomView";
        CustomView layout;
        WebView webView;
        int h = 0;
        int w = 0;
        ThemedReactContext reactContext;


        @Override
        public String getName() {
            return REACT_CLASS;
        }

        @Override
        protected CustomView createViewInstance(ThemedReactContext reactContext) {
            /**String html = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>HTML5 Boilerplate</title></head><body style='margin:0;padding:0;'><h1>Page Title 2</h1></body></html>";
            html += "<script>";
            html += "window.onload = function(){";
            html += "javascript:JSInterface.ResizeWebView(document.body.scrollHeight)";
            html += "};";
            html += "</script>";**/
            this.reactContext = reactContext;
            layout = new CustomView(reactContext);
            return layout;
        }
        
        @ReactProp(name = "messageId")
        public void setMessageId(LinearLayout view, int messageId) {
            layout.setMessageId(String.valueOf(messageId));
        }
        
        @ReactProp(name = "message")
        public void setWebviewHtml(LinearLayout view, String html) {


            String uniqueId = UUID.randomUUID().toString().replace("-", "");
            uniqueId = "APPJS" + uniqueId;
            //Toast.makeText(reactContext, "uniqueId: " + uniqueId, Toast.LENGTH_SHORT).show();
            html = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>HTML5 Boilerplate</title><script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js' integrity='sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==' crossorigin='anonymous' referrerpolicy='no-referrer'></script></head><body style='margin:0;padding:0;word-wrap:break-word;'>" + html + "</body></html>";

            //oast.makeText(reactContext, "html: " + html, Toast.LENGTH_SHORT).show();
            html += "<script>";
            html += "$(document).ready(function() {";
            html += "javascript:" + uniqueId + ".ResizeWebView($(document).height())";
            html += "});";
            html += "</script>";
            layout.setWebviewHtml(html, uniqueId);
        }

        @Override
        public @Nullable Map getExportedCustomDirectEventTypeConstants() {
            return MapBuilder.of("myCallback",
                MapBuilder.of("registrationName", "myCallback"));
        }


    }

This is the CustomView:

    package com.poller;
    import android.widget.LinearLayout;
    import android.content.Context;
    import android.webkit.WebView;
    import android.widget.Toast;
    import android.os.Bundle;
    import android.view.ViewTreeObserver;
    import android.view.ViewTreeObserver.OnPreDrawListener;
    import android.webkit.WebViewClient;
    import android.webkit.WebSettings;
    import com.facebook.react.bridge.Arguments;
    import com.facebook.react.bridge.ReactContext;
    import com.facebook.react.bridge.WritableMap;
    import com.facebook.react.uimanager.events.RCTEventEmitter;
    import android.view.View;

    public class CustomView extends LinearLayout {
        private Context context;
        ViewTreeObserver viewTreeObserver;
        WebView webView;
        String messageId = "";
        public CustomView(Context context) {
            super(context);//ADD THIS
            this.context = context;
            //setContentView(R.layout.webview_layout);
            inflate(context, R.layout.webview_layout, this);

            //Toast.makeText(context, "html " + html, Toast.LENGTH_SHORT).show();
            webView = (WebView) findViewById(R.id.webview);
        }

        
        public void setMessageId(String messageId) {
            this.messageId = messageId;
        }

        public void setWebviewHtml(String html, String uniqueId) {
            //Toast.makeText(context, "html2: " + html, Toast.LENGTH_SHORT).show();
            webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.addJavascriptInterface(new JSInterface(webView, context, this), uniqueId);
        }

        public void sendWebViewHeight(final float height){
            WritableMap map = Arguments.createMap();
            map.putString("messageId", String.valueOf(messageId));
            map.putString("wVheight", String.valueOf(height));
            final ReactContext context = (ReactContext) getContext();
            context.getJSModule(RCTEventEmitter.class).receiveEvent(
                getId(),
                "myCallback",
                map
            );
        }
    }

And this is my JavaScript Interface so that the WebView can talk to the Native Code:

    package com.poller;

    import android.content.Context;
    import android.webkit.WebView;
    import android.widget.Toast;
    import android.content.res.Resources;
    import android.webkit.JavascriptInterface;

    public class JSInterface{

        private WebView mAppView;
        private Context context;
        public CustomView cv;
        public JSInterface  (WebView appView, Context context, CustomView cv) {
            this.mAppView = appView;
            this.context = context;
            this.cv = cv;
        }

        @JavascriptInterface
        public void ResizeWebView(final float height) {
            float webViewHeight = height;//(height * context.getResources().getDisplayMetrics().density);
            cv.sendWebViewHeight(webViewHeight);
            //Toast.makeText(context, String.valueOf(webViewHeight), Toast.LENGTH_SHORT).show();
        }
    }

In my React Native Component I import the MyCustomeView:

    const iface = {
        name: 'PollChat',
        propTypes: {
        myCallback: PropTypes.func,
        ...ViewPropTypes,
        },
    };
    const MyCustomView = requireNativeComponent('MyCustomView', iface);

I have uses Iface because I need to send back the height of the WebView, so a call-back is needed to set the Components height when the state updates in the React Native Component.

This is the Component’s that renders and talks to the Native UI Component:

<MyCustomView messageId={e["message"]["mess"].id} message={e["message"]["mess"].message} style={{flex:1, height:heightWV[index] ? heightWV[index].height : 0}} myCallback={setChatWebViewHeight}/>

And this is the callback where native code sends back the message id and the webviews height:

const setChatWebViewHeight = (e) =>{
    e.persist();
    const hasMessage = messageId.find((messageIdArr) => messageIdArr === parseInt(e.nativeEvent.messageId));
    
    //If message has already loaded then dont update its state
    if(!hasMessage){

        var heightData = {
            height: parseFloat(e.nativeEvent.wVheight),
            messsageId: parseInt(e.nativeEvent.messageId)
        }

        console.log(e.nativeEvent.messageId);
        console.log(e.nativeEvent.wVheight);
        setMessageId(oldArray => [...oldArray, parseInt(e.nativeEvent.messageId)]);
        setHeightWV(oldArray => [...oldArray, heightData]);
        
    }

  }

This is the state that holds the height and message id’s:

const [messageGlobalId, setMessageGlobalId] = useState([]);
const [heightWV, setHeightWV] = useState([]);

The WebView layout xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<WebView
    android:id="@+id/webview"
    android:padding="20dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000" />


 </LinearLayout>

Everything works but the problem is that the messages takes time to update the ui, I believe its because the app cant handle more than one message rendering the WebView’s.

My question is, is there a faster way of updating the ui? because with this code the ui takes 2 minutes to finally load just 11 messages.

Here is a 2-3 minute video of how the app is reacting to the state:

https://jumpshare.com/s/7AgxFaXpq8XX4g0j4WDw

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật