When to use Javascript’s createContextualFragment function?

Asked

Viewed 35 times

0

I am refactoring a function that uses Jquery to use pure javascript only, the function is very simple, it performs a request ajax which takes back an HTML structure that can contain a tag script, currently the attribution of this return is similar to this.

$('#exemplo').html(retorno);

The Jquery snippet works very well and runs the tag script when included in the return, but when I try to switch to a direct assignment, although the HTML elements are created, the tag script is not executed.

document.getElementById('exemplo').innerHTML = retorno;

After some research I understood that tags scripts are not actually executed when we assign the property innerHTML of an element, so I found the function createContextualFragment and using the same as follows everything works well.

elemento.append(document.createRange().createContextualFragment(retorno));

However, I’m not familiar with the functions createRange and createContextualFragment, therefore, I would like to know the following.

  1. The createContextualFragment function is the best alternative to performing the described task?
  2. What are the implications of using this function (performance/compatibility)?
  3. When I should and when I should not use this function?
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.