Web browsers may not interpret the content of a <script>
element if it is added to the document using targetElement.innerHTML
. This could be the issue you are facing.
A recommended solution would be to utilize a reliable framework like jQuery for handling such situations. Frameworks like jQuery have already addressed the challenges of injecting scripts into the DOM safely and efficiently. It's usually best to leverage existing solutions rather than reinventing the wheel, unless minimizing library dependencies is crucial for your project's requirements.
An alternative approach to solving this problem is to separate the JavaScript code from the HTML content in the response obtained via Ajax. This can be achieved by making two separate requests (although this might impact performance) or by structuring the JavaScript and HTML within a JSON object (which could potentially complicate maintenance).
Below is an example implementation:
<script>
function load_content(){
var req = new XMLHttpRequest();
req.open("GET", "ajax.json", true);
req.onreadystatechange = function (e){
if (req.readyState === 4){
if (req.status === 200){
// Injecting JavaScript and HTML content into the DOM
var json = JSON.parse(req.responseText);
document.getElementById("target").innerHTML = json.html;
eval(json.js);
} else {
console.log("Error", req.statusText);
}
}
};
req.send(null);
}
</script>
<a href="#" onclick="load_content()">Load more stuff</a>
<div id="target"></div>
The content of the document ajax.json
hosted on the server should resemble the following structure:
{
"js": "window.bar = function (){ console.log(\"bar\"); return false; }",
"html": "<p><a href=\"#\" onclick=\"bar();\">Log a message</a></p>"
}
If you opt for this method, remember to either:
- namespace your functions:
MyApp.foo = function (){ ... };
, or
- explicitly add your functions to the global namespace:
window.foo = function (){ ... };
.
This caution is due to the fact that the use of eval
executes within the current scope, causing potential scoping issues with function availability. In the provided example, the latter option was chosen for simplicity, but understanding this distinction is crucial for successful implementation.
Before proceeding with this approach, it is highly recommended to review the article on When is JavaScript's eval() not evil? to ensure safe and appropriate usage of eval()
.