I want to replace some specific tags by using JavaScript.
The tags I want to replace are these <!--
and -->
. Between these two tags 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);
Extract the contents of the script between
<!-- -->
using regular expressions, then create an elementscript
and add it to the end of the body for execution.Example
However, I don't see any point in what you're doing, unless you do some processing when the page loads and then add the scripts. Just don't do that; if you want to load scripts at the end of parsing and loading the DOM use the attribute
defer
on the scripts, as @Lorthas indicates.Replace creates a new string with the replaced text, it does not modify the current string.
Therefore you should do:
Reference: String.prototype.replace on MDN
I think that for readability issues you should have the scripts in a file apart from the html and more if you want to load them later.
If you want to load it later, it is as easy as loading them by adding them to the html. I leave you a small function that does this:
You just have to pass the path/name of the file and you will have it available.
Hope this can help you.
If what you want is to simply load certain scripts after having loaded the DOM (which I have understood at least) read the following:
According to https://m.genbetadev.com/javascript/javascript-defer-vs-async 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.
You can also to make sure put the script tag before closing the body. Async and Defer are from HTML5.