Home >Web Front-end >JS Tutorial >Why Doesn\'t the `onload` Event Fire When Appending a Script Element Using jQuery?
OnLoad Event Problem with Script Tag
In an attempt to load scripts in a sequence, an issue arises where the onload event fails to trigger. The following code snippet demonstrates the problem:
function loadScripts(scripts){ var script = scripts.shift(); var el = document.createElement('script'); el.src = script; el.onload = function(script){ console.log(script + ' loaded!'); if (scripts.length) { loadScripts(scripts); } else { console.log('run app'); MK.init(); } }; $body.append(el); }
The onload event does not fire when the script element is appended to the DOM using jQuery ($body.append(el)). However, using native JavaScript document.body.appendChild(el) triggers the event as intended.
Solution:
To resolve this issue, modify the code as follows:
function loadScripts(scripts){ var script = scripts.shift(); var el = document.createElement('script'); $body.append(el); el.onload = function(script){ console.log(script + ' loaded!'); if (scripts.length) { loadScripts(scripts); } else { console.log('run app'); MK.init(); } }; el.src = script; }
By attaching the script to the DOM before setting the src attribute, the onload event will fire as expected. Additionally, consider using jQuery's getScript() method for cross-browser compatibility.
The above is the detailed content of Why Doesn\'t the `onload` Event Fire When Appending a Script Element Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!