Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

javascript - Script loading: jQuery vs vanilla JS -- why a difference?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...