In a recent discussion on Stack Overflow, the topic of loading JavaScript code to an HTML file at runtime was raised. One method suggested involves simple loading an external JS file and executing it. However, there are two key issues with this approach: the timing of execution is uncertain and customization options are limited.
The following code snippet was shared:
var elemScript=document.createElement('script');
elemScript.setAttribute('type', 'text/javascript');
elemScript.setAttribute('language', 'javascript');
var txt = document.createTextNode(result);
elemScript.appendChild(txt);
document.head.appendChild(elemScript);
I have been using this code within an HTTP request where the variable result contains customized code generated by a PHP script. This allows me to dispatch functions that require this dynamic code.
Unfortunately, this solution does not work in Internet Explorer 8 or older versions. Should we continue exploring ways to make it compatible with these outdated browsers, or is it time to move on?
Any suggestions for alternative approaches?