1

I am working on embedded WKWebView (a browser view on iOS), so I don't want/can't use any libraries and need to achieve the following purely in JavaScript.

While content of the web view is loading, I want to clear previous content, and display something like "Loading...".

The most obvious way is to

document.body.innerHTML = "Loading...";

(method 1)

But the problem is it leaves other elements (e.g. scripts, styles) of the page intact, while I need the style to be reset (e.g. clear background, fonts, etc)

There is a way to clear everything by removing HTML element, which is good

document.documentElement.remove()

(method 2)

But how can I then add a new HTML element with new content?

So is there a way to add a new HTML element using method 2, or to clear style, scripts, etc using method 1?

Note: Loading... is just an example text I want to use, actual content could be proper HTML if it's important.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
timbre timbre
  • 12,648
  • 10
  • 46
  • 77
  • Do you need to clear the content? For example we have a `popup` div that will display and hide all else. Would that suffice? – Bibberty Aug 22 '19 at 20:53
  • Why exactly do you want to do it this way? why not implement something like a `modal window`? – bitznbytez Aug 22 '19 at 20:53
  • I don't know which site is loaded, so who knows how those popups are styled? – timbre timbre Aug 22 '19 at 20:55
  • 1
    @ Bhojendra Rauniyar it;'s a good idea to read a question before you mark it as duplicate. I was NOT asking how to clear content, I was asking how to load new content. – timbre timbre Aug 22 '19 at 21:07
  • Plus, there are much better duplicates: [What other options for replacing entire HTML document via W3C DOM?](https://stackoverflow.com/q/4297877/215552), [Replacing Entire Page Including Head Using Javascript](https://stackoverflow.com/q/4292603/215552), [Replace entire HTML document in-place](https://stackoverflow.com/q/2825586/215552)... – Heretic Monkey Aug 22 '19 at 21:33

2 Answers2

1

Try

document.documentElement.remove();

var html = document.createElement('html');
var body = document.createElement('body');

html.appendChild(body);
document.appendChild(html);

document.body.innerHTML = `<span>Here your arbitrary html</span>`;
<div>x</div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

Store the nodes and show loading

var head = document.head.innerHTML;
var body = document.body.innerHTML;
document.head.innerHTML = '';
document.body.innerHTML = 'Loading...';

undo

document.head.innerHTML = head;
document.body.innerHTML = body;

This way you can show the loading stuff.

tom
  • 9,550
  • 6
  • 30
  • 49