Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why does vanilla JS's onload work where jQuery's load on does not when it comes to loading scripts?

So...

thisScript.onload=function Event triggers as expected.

$(thisScript).bind({load:function Event does not trigger

$(thisScript).on({load:function Event does not trigger

JS load and jQuery onload both work fine when it comes to loading

thisImg.onload=function Event triggers as expected

is the same as...

$(thisImg).bind({load:function Event triggers as expected

$(thisImg).on({load:function Event triggers as expected

...but not for scripts.

I'm aware of $.getScript but I'm curious about the above discrepancy.

Question Is there an event binding for jQuery that works for script loading?

The following test is revealing:

window.onload=()=>
    var thisSrc, thisScript, thisTest;
    thisSrc="testScript.js"; //See contents below
    thisTest="JS";
    //thisTest="JQ";
    
    if(thisTest=="JS"){
        thisScript=document.head.appendChild(document.createElement("script"));
        thisScript.onload=function(){
            alert("Event Triggered"); //EVENT TRIGGERS AND THE SCRIPT LOADS.
        }
        thisScript.src=thisSrc;

    }else if(thisTest=="JQ"){
        thisScript=$("<script>")
            .attr({src:thisSrc})
//          .bind({
            .on({
                load:function(){
                    alert("Event Triggered");  //EVENT DOES NOT TRIGGER BUT THE SCRIPT LOADS.
                }
            })
            .appendTo(document.head)[0];
    }
}

Contents of testScript.js:

alert("Script Loaded");

Both JS and jQuery successfully load the script. It's just the JQ event listener that doesn't trigger.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

Resolved -- issue is order of commands.

src needs to be defined after the <script> element is in the DOM and the listeners are assigned.

So this works reliably...

$("<script>")
    .appendTo(document.head)
    .on({
         load:function(){
              alert("Event Triggered");
         }
    })
    .attr({src:thisSrc});

Order of .on and .appendTo can be reversed, but have happen before .attr


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...