1

I've created an external/public JavaScript library.

As I am testing it on an Angular 1.x web app by including the script in the <HEAD>, I've found that it breaks the Angular app by making clicks do nothing.

After hours of debugging namespace, properties, and functions; I've finally found the culprit is when I insert HTML elements into the webpage. My JS library is currently using this code to insert HTML into the webpage. How would I go about making it support Angular apps (or SPAs in general)?

var HTML_ELEMENTS = ['<h1>Hi</h1>', '<div>Hello again.</div>'];

for (var i = 0; i < HTML_ELEMENTS.length; i++) {
  document.body.innerHTML += HTML_ELEMENTS[i];
};

One of the reasons I add the HTML elements to the bottom of document.body is because I set these elements to have the highest z-index in the page, so any competing elements will yield the z-index to my inserted HTML elements.

2
  • 1
    innerHTML += will replace the whole element content with the newly rendered HTML, containing of the current innerHTML + the new string you appended. In the process, all existing descendant elements will be destroyed, and then re-created, plus the new ones. Therefor you loose all previously attached event handlers, etc. If you want to do this in vanilla JS, you'll have to go the DOM way and use createElement, createTextNode, appendChild ... Commented Oct 21, 2017 at 2:33
  • 1
    Or, you restrict all your external library's doings to a specific child element, and all your angular stuff to everything else - prepare <div id="plugincontainer"></div> in your document, and then use document.getElementById("plugincontainer").innerHTML += Commented Oct 21, 2017 at 2:36

1 Answer 1

1

Answering my own question with my implementation. All credit goes to @Cbroe for pointing me in the right direction.

Basically, you cannot use document.body.innerHTML with Angular, so here's what I ended up using instead:

var HTML_ELEMENTS = ['<h1>Hi</h1>', '<div>Hello again.</div>'];

for (var i = 0; i < HTML_ELEMENTS.length; i++) {
  var child = document.createElement('div');
  child.innerHTML = HTML_ELEMENTS[i];
  child = child.firstChild;
  document.body.appendChild(child);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.