Skip to content

Instantly share code, notes, and snippets.

@gengns
Last active May 26, 2020 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gengns/30d2d5eb491ab1c35dce7d6f7d932f99 to your computer and use it in GitHub Desktop.
Save gengns/30d2d5eb491ab1c35dce7d6f7d932f99 to your computer and use it in GitHub Desktop.
Get a local html file to insert into your Cordova Single Page Application
/**
Get local html files (views/widgets) to insert into your SPA
@param path ex:
path = 'file:///android_asset/www/view/page.html'
@param success
@param failure
*/
function get_html_file(path, success, failure) {
const xhr = new XMLHttpRequest()
xhr.open('GET', path)
xhr.onload = () => {
if (xhr.status == 200)
success(xhr.response)
else if (failure)
failure(xhr.status)
}
xhr.send()
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="container"></div>
</body>
<script src="js/get_html_file.js"></script>
<script src="js/page.js"></script>
</html>
<div id="page">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
/*
@file page.js
@description View
*/
const page = (() => {
function load() {
get_html_file('file:///android_asset/www/view/page.html', data => {
document.querySelector('#container').innerHTML = data
})
}
return {
load: load
}
})()
@gengns
Copy link
Author

gengns commented Apr 22, 2018

You can use Axios as well instead of the typical XMLHttpRequest:

axios.get('file:///android_asset/www/view/page.html').then(r => {
  document.querySelector('#container').innerHTML = r.data
})

As you can see here, we are using these approach to load different views into an Android SPA.

Note: Remember that Fetch API do not support URL scheme 'file' :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment