How to replace tags with JavaScript?

2

I want to replace specific tags by using JavaScript.

The labels I want to replace are these <!-- and --> . Between these two labels I have code that will be executed when the page is fully loaded.

This is my code:

function listen(){
var html = document.getElementsByTagName('html')[0];
[].slice.call(html).forEach(function(el, i){
el.innerHTML.replace('<!--', '<script>').replace('-->', '</script>');
});
}

window.addEventListener('DOMContentLoaded', function(){
listen();
}, false);
    
asked by Eddy Otsutsuki 16.03.2017 в 06:20
source

4 answers

4

Extract the content of the script between <!-- --> using regular expressions, then create an element script and add it to the end of the body for execution.

Example

let scriptText = "<!-- alert('Hola'); -->";
let matches = scriptText.match(/<!--(.*?)-->/);
let code = matches[1].trim();

let script = document.createElement('script');
script.textContent = code;
document.body.appendChild(script);

However, I do not see any sense in what you do, unless you perform some process when you load the page and then add the scripts. Just do not do that; if you want to load scripts at the end of the parse and load the DOM use the defer attribute in the scripts, as indicated by @Lorthas.

    
answered by 16.03.2017 / 14:10
source
2

Replace creates a new string with the replaced text, it does not modify the current string.

Therefore you should do:

el.innerHTML = el.innerHTML.replace('<!--', '<script>').replace('-->', '</script>');

Reference: String.prototype.replace in MDN

    
answered by 16.03.2017 в 12:11
1

I think that for readability issues you should have the scripts in a file other than the html and more if you want to load them afterwards.

If you want to load it later, it's as easy as loading them by adding them to the html. I leave you a small function that does this:

function loadScript(url)
{
    document.body.appendChild(document.createElement("script")).src = url;
}

You just have to pass the path / name of the file and you will have it available.

I hope it serves you.

    
answered by 16.03.2017 в 12:42
0

If you just want to load certain scripts after loading the DOM (which I understood at least) read the following:

According to link If you add the defer attribute to the script tag, the Javascript code will not be executed until all the elements of the page have been loaded.

<html>
  <head>
    <script defer src="url/archivo.js">
  </head>
  <body>
  <body>
<html>

You can also make sure to put the script label before closing the body. Async and Defer are from HTML5.

    
answered by 16.03.2017 в 14:14