Dynamically added script tags not executed.
Categories
(Core :: DOM: Core & HTML, defect)
Tracking
()
People
(Reporter: mail, Unassigned)
Details
(Keywords: testcase-wanted)
Comment 1•14 years ago
|
||
Comment 2•14 years ago
|
||
Comment 3•14 years ago
|
||
Comment 4•10 years ago
|
||
Comment 5•10 years ago
|
||
Comment 7•10 years ago
|
||
| Assignee | ||
Updated•6 years ago
|
Comment 8•6 years ago
|
||
The dynamically added script in the example below will not be executed on FireFox (nor on Safari), but will on Chrome:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Test dynamically added script</title>
<script>
setTimeout(_=>{
alert("Adding a new script");
let newScript = document.createElement('script');
newScript.innerHTML = "window.onload = _=>{alert('Script added and executed');}";
document.getElementsByTagName('head')[0].appendChild(newScript);
}, 0);
</script>
</head>
<body>
</body>
</html>
The message "Adding a new script" appears but "Script added and executed" does not. To make it work, one needs to remove timeout.
Don't ask why I needed this :)
Comment 9•6 years ago
|
||
Correction to the above: Probably the execution of the added script on Chrome is still an artifact because it happens when the above example is served from a server not from a local file, and setting the timeout to >~ 10 ms stops the execution.
Comment 10•6 years ago
|
||
Right, that code is fundamentally racy: it depends on whether the setTimeout fires before the load event fires, which depends on whether the rest of the HTML was received fast enough, on timer scheduling, etc, etc.
That is, the dynamically added script is executing in all cases. What changes is whether it sets window.onload before the load event has fired or after. If it sets it after, the alert won't be shown.
Description
•