从Assets文件夹加载CSS JS

时间:2021-05-18 00:26:42

I've been searching for hours for a solution; and although there are similar situations, mine I think is a bit different. I have a website that I'm loading into webview

我一直在寻找解决方案的时间;虽然有类似的情况,但我认为我的情况有点不同。我有一个网站,我正在加载到webview

    setContentView(R.layout.activity_main);
    WebView myWebView = (WebView) findViewById(webview);
    myWebView.loadUrl("http://my-website.com/index.php");
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    myWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.toString());
            return true;
        }
    }); }

It's loading the website fine. No issues. What I'm trying to do (because there are alot of CSS & JS files) is load these files from the assets folder of the Android App - I'm trying to make the page load faster.

它正在加载网站。没有问题。我正在尝试做什么(因为有很多CSS和JS文件)是从Android应用程序的assets文件夹加载这些文件 - 我正在尝试使页面加载更快。

<link href="file:///android_asset/css/keyframes.css" rel="stylesheet" type="text/css">
<link href="file:///android_asset/css/materialize.min.css" rel="stylesheet" type="text/css">
<link href="file:///android_asset/css/swiper.css" rel="stylesheet" type="text/css">
<link href="file:///android_asset/css/swipebox.min.css" rel="stylesheet" type="text/css">
<link href="file:///android_asset/css/style.css" rel="stylesheet" type="text/css">

It is currently not loading any of my CSS files which are called this way. I really don't mean to pester anybody with a simple problem, It's just been bothering me and I'm not good with Java. Also, this is NOT a local HTML page. This is a PHP page loaded from a remote server.

它目前没有加载任何以这种方式调用的CSS文件。我真的不是故意用一个简单的问题纠缠任何人,这只是困扰我,我对Java不好。此外,这不是本地HTML页面。这是从远程服务器加载的PHP页面。

4 个解决方案

#1


1  

I am not a mobile developer, but I am a web developer that did write some webview pages for my mobile developer colleagues.

我不是移动开发人员,但我是一名Web开发人员,为我的移动开发人员同事编写了一些webview页面。

As far as I know, you are not able to access file system in webview. However, you can let your app cache the css / js files.

据我所知,您无法访问webview中的文件系统。但是,您可以让您的应用缓存css / js文件。

viewer.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT)

(This is from an answer here on *) (and here is the document on cache settings)

(这是来自*的答案)(这里是关于缓存设置的文档)

By using the default cache settings, the CSS / JS files will be cached after downloaded in the first time, as it was cached in normal browser. So you can simply use

通过使用默认缓存设置,CSS / JS文件将在第一次下载后缓存,因为它是在普通浏览器中缓存的。所以你可以简单地使用

<link href="https://your.domain/css/style.css" rel="stylesheet" type="text/css">

to achieve the faster page load you want.

实现您想要的更快的页面加载。

#2


0  

If you want to load css and js from local asset folder then first you need to download your webpage and then after you need to pass in web browser like following way,

如果你想从本地资产文件夹加载css和js,那么首先需要下载你的网页,然后你需要通过以下方式传入网络浏览器,

Download Data Like using this :

下载数据就像使用这个:

public String getHtmlContent(String urlToLoad) {
        String outputStr = "";
        BufferedReader inputString = null;
        try {
            URL urlLoad = new URL(urlToLoad);
            inputString = new BufferedReader(new InputStreamReader(urlLoad.openStream()));
            String str;
            while ((str = inputString.readLine()) != null) {
                outputStr += str;
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            if (inputString != null) {
                try {
                    inputString.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return outputStr;
    }

Then after you need to put your js and css file inside of asset folder and then need to define a url in web page like following

然后你需要将你的js和css文件放在资产文件夹中,然后需要在网页中定义一个url如下

<script src="file:///android_asset/jquery.min.js" type="text/javascript"></script>

You need set all the url using like file:///android_asset/ then after your css or js name,

您需要使用like file:/// android_asset /然后在您的css或js名称之后设置所有网址,

After all thing finish you need to set your webpage content with webview like following

完成所有事情后,您需要使用webview设置您的网页内容,如下所示

String webData = getHtmlContent("http://webisteaddress.com/index.html");
    mWebView.loadDataWithBaseURL("file:///android_asset/", webData, "text/html", "utf-8", "");

#3


0  

Use this function to load CSS & JavaScript inside your WebView: inject both CSS & JavaScript inside onCreate() on WebViewClient:

使用此函数在WebView中加载CSS和JavaScript:在WebViewClient上的onCreate()中注入CSS和JavaScript:

     webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url)
        {
            injectJavaScript(view);
            injectCSS();

         }

Create two methods to inject JavaScript & CSS(from res/raw):

创建两个方法来注入JavaScript和CSS(来自res / raw):

    private boolean injectJavaScript(WebView view){
        view.loadUrl("javascript:(function() { " +
            "var head = document.getElementsByTagName('header')[0];"
            + "head.parentNode.removeChild(head);" + "console.log('true');"+
            "})()");
        view.loadUrl("javascript:(function() { " +
            "var footer = document.getElementsByTagName('footer')[0];"
            + "footer.parentNode.removeChild(footer);" +
            "})()");
        view.loadUrl("javascript:(function() { " +
            "var nav = document.getElementsByTagName('nav')[0];"
            + "nav.parentNode.removeChild(nav);" +
            "})()");
        view.loadUrl("javascript:(function() { " +
            "var set = document.getElementsByClassName('banner');"
            + "set[0].style.margin = '0px';" +
            "})()");
    return true;
    }
    private void injectCSS() {
    try {
        InputStream inputStream = getResources().openRawResource(R.raw.css);
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        inputStream.close();
        String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
        wv1.loadUrl("javascript:(function() {" +
                "var parent = document.getElementsByTagName('head').item(0);" +
                "var style = document.createElement('style');" +
                "style.type = 'text/css';" +
                "style.innerHTML = window.atob('" + encoded + "');" +
                "parent.appendChild(style)" +
                "})()");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

This worked for me like a charm.

这对我来说就像一个魅力。

#4


0  

Loading CSS using <link rel="stylesheet" href=""/> is going to be deprecated in March 2018. I just got a warning message for this in Developer Console today.

使用 加载CSS将在2018年3月弃用。我今天在Developer Console中收到了一条警告消息。

This is because nothing renders on the page till all the CSS has loaded.

这是因为在所有CSS加载之前,页面上没有任何渲染。

So instead, the suggestion is that we load the CSS using JavaScript, and have a small inline stylesheet to render the basic look of the page; plus separate stylesheets for each section of the page, which are called from the <body> rather than the <head>.

所以相反,建议是我们使用JavaScript加载CSS,并使用一个小的内联样式表来呈现页面的基本外观;加上页面每个部分的单独样式表,从而不是调用。

#1


1  

I am not a mobile developer, but I am a web developer that did write some webview pages for my mobile developer colleagues.

我不是移动开发人员,但我是一名Web开发人员,为我的移动开发人员同事编写了一些webview页面。

As far as I know, you are not able to access file system in webview. However, you can let your app cache the css / js files.

据我所知,您无法访问webview中的文件系统。但是,您可以让您的应用缓存css / js文件。

viewer.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT)

(This is from an answer here on *) (and here is the document on cache settings)

(这是来自*的答案)(这里是关于缓存设置的文档)

By using the default cache settings, the CSS / JS files will be cached after downloaded in the first time, as it was cached in normal browser. So you can simply use

通过使用默认缓存设置,CSS / JS文件将在第一次下载后缓存,因为它是在普通浏览器中缓存的。所以你可以简单地使用

<link href="https://your.domain/css/style.css" rel="stylesheet" type="text/css">

to achieve the faster page load you want.

实现您想要的更快的页面加载。

#2


0  

If you want to load css and js from local asset folder then first you need to download your webpage and then after you need to pass in web browser like following way,

如果你想从本地资产文件夹加载css和js,那么首先需要下载你的网页,然后你需要通过以下方式传入网络浏览器,

Download Data Like using this :

下载数据就像使用这个:

public String getHtmlContent(String urlToLoad) {
        String outputStr = "";
        BufferedReader inputString = null;
        try {
            URL urlLoad = new URL(urlToLoad);
            inputString = new BufferedReader(new InputStreamReader(urlLoad.openStream()));
            String str;
            while ((str = inputString.readLine()) != null) {
                outputStr += str;
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            if (inputString != null) {
                try {
                    inputString.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return outputStr;
    }

Then after you need to put your js and css file inside of asset folder and then need to define a url in web page like following

然后你需要将你的js和css文件放在资产文件夹中,然后需要在网页中定义一个url如下

<script src="file:///android_asset/jquery.min.js" type="text/javascript"></script>

You need set all the url using like file:///android_asset/ then after your css or js name,

您需要使用like file:/// android_asset /然后在您的css或js名称之后设置所有网址,

After all thing finish you need to set your webpage content with webview like following

完成所有事情后,您需要使用webview设置您的网页内容,如下所示

String webData = getHtmlContent("http://webisteaddress.com/index.html");
    mWebView.loadDataWithBaseURL("file:///android_asset/", webData, "text/html", "utf-8", "");

#3


0  

Use this function to load CSS & JavaScript inside your WebView: inject both CSS & JavaScript inside onCreate() on WebViewClient:

使用此函数在WebView中加载CSS和JavaScript:在WebViewClient上的onCreate()中注入CSS和JavaScript:

     webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url)
        {
            injectJavaScript(view);
            injectCSS();

         }

Create two methods to inject JavaScript & CSS(from res/raw):

创建两个方法来注入JavaScript和CSS(来自res / raw):

    private boolean injectJavaScript(WebView view){
        view.loadUrl("javascript:(function() { " +
            "var head = document.getElementsByTagName('header')[0];"
            + "head.parentNode.removeChild(head);" + "console.log('true');"+
            "})()");
        view.loadUrl("javascript:(function() { " +
            "var footer = document.getElementsByTagName('footer')[0];"
            + "footer.parentNode.removeChild(footer);" +
            "})()");
        view.loadUrl("javascript:(function() { " +
            "var nav = document.getElementsByTagName('nav')[0];"
            + "nav.parentNode.removeChild(nav);" +
            "})()");
        view.loadUrl("javascript:(function() { " +
            "var set = document.getElementsByClassName('banner');"
            + "set[0].style.margin = '0px';" +
            "})()");
    return true;
    }
    private void injectCSS() {
    try {
        InputStream inputStream = getResources().openRawResource(R.raw.css);
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        inputStream.close();
        String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
        wv1.loadUrl("javascript:(function() {" +
                "var parent = document.getElementsByTagName('head').item(0);" +
                "var style = document.createElement('style');" +
                "style.type = 'text/css';" +
                "style.innerHTML = window.atob('" + encoded + "');" +
                "parent.appendChild(style)" +
                "})()");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

This worked for me like a charm.

这对我来说就像一个魅力。

#4


0  

Loading CSS using <link rel="stylesheet" href=""/> is going to be deprecated in March 2018. I just got a warning message for this in Developer Console today.

使用 加载CSS将在2018年3月弃用。我今天在Developer Console中收到了一条警告消息。

This is because nothing renders on the page till all the CSS has loaded.

这是因为在所有CSS加载之前,页面上没有任何渲染。

So instead, the suggestion is that we load the CSS using JavaScript, and have a small inline stylesheet to render the basic look of the page; plus separate stylesheets for each section of the page, which are called from the <body> rather than the <head>.

所以相反,建议是我们使用JavaScript加载CSS,并使用一个小的内联样式表来呈现页面的基本外观;加上页面每个部分的单独样式表,从而不是调用。