Home > Web Front-end > JS Tutorial > body text

Why Doesn\'t the `onload` Event Fire When Appending a Script Element Using jQuery?

Barbara Streisand
Release: 2024-11-04 02:45:02
Original
312 people have browsed it

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);
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template