简体   繁体   中英

calling getScript inside an ajax load callback function

Can somebody please explain this to me. The goal here is to load via an ajax call an external html, and then load and execute an external script associated with that html code.

Code A:

$('#content').load(toLoad,function(){
        $.getScript("toLoadScript.js");
});

Code B:

$('#content').load(toLoad,showNewContent());
function showNewContent() {
    $.getScript("toLoadScript.js");
}

Code C:

$('#content').load(toLoad,showNewContent);
function showNewContent() {
    $.getScript("toLoadScript.js");
}

Why is it that only Code C succesfully loads and executes the script while the other 2 doesn't.

question related to: Jquery: Run script after ajax load()

Partial answer: why Code B doesn't work

In Code B you are invoking .load as follows:

$('#content').load(toLoad,showNewContent());

Which essentially breaks down into:

var newContent = showNewContent();
$('#content').load(toLoad,newContent);

So you are invoking showNewContent and passing the result of that into .load .

This is not what you want to do. Instead you should pass the function itself (and not its result) to load :

$('#content').load(toLoad,showNewContent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM