Explanation first. There are several ways to do that but in my opinion the simplest would be to add the relevant script and style elements to the top of the HTML after the DOM is loaded. So your external JS file consists basically of a listener for the DOMContentLoaded
event that does two things:
- inject a script and a style element into the DOM
- call the initialisation code for hightlight.js as soon as the script has finished loading.
Untested (!) code now. I suggest to test it in a basic HTML document in your browser’s web developer tools first.
Edit Fixed typo in code according to @fredap’s post below.
document.addEventListener('DOMContentLoaded', () => {
const script = document.createElement('script');
script.type = 'text/javascript';
/* Initialize Highlight code as soon as the script is loaded */
script.addEventListener('load', () => hljs.highlightAll() );
script.src = 'Script URL';
const style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = 'Style Sheet URL';
document.head.append(script, style);
})
There’s some more information on MDN
An alternative solution would be to use Ajax in the DOMContentLoaded
listener that loads the JS file and executes it. I find that a bit clumsy and since it requires the use of eval
a security burden.