Script Onload Event Not Triggering
When attempting to sequentially load a series of scripts, the onload event fails to trigger. An examination of the code below reveals the issue:
<code class="javascript">var scripts = [ '//cdnjs.cloudflare.com/ajax/libs/less.js/1.3.3/less.min.js', '//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0-rc.3/handlebars.min.js', MK.host+'/templates/templates.js' ]; function loadScripts(scripts){ var script = scripts.shift(); var el = document.createElement('script'); el.src = script; // Removed: el.src assignment here el.onload = function(script){ console.log(script + ' loaded!'); if (scripts.length) { loadScripts(scripts); } else { console.log('run app'); MK.init(); } }; $body.append(el); // Added: el appended before onload el.src = script; // Moved: el.src assignment here } loadScripts(scripts);</code>
The issue stems from the incorrect placement of the onload event listener and the assignment of the src attribute. The correct code is:
<code class="javascript"> el.onload = function(script){ console.log(script + ' loaded!'); if (scripts.length) { loadScripts(scripts); } else { console.log('run app'); MK.init(); } }; $body.append(el); el.src = script;</code>
By ensuring that the script is appended to the DOM before attaching the onload event and by setting the src attribute after the onload event, the expected behavior is achieved. Additionally, it is important to note that for IE support, the readystate should be checked. For jQuery users, the getScript() method provides a convenient alternative for script loading.
The above is the detailed content of Why Doesn't My Script Onload Event Trigger When Loading Multiple Scripts Sequentially?. For more information, please follow other related articles on the PHP Chinese website!