Loading scripts after page load?

后端 未结 7 1658
粉色の甜心
粉色の甜心 2020-11-27 15:16

I work with an advertising company, where we tag certain pages to track activity. A client of mine wants to fire off a javascript tag to track activity AFTER the page has fi

7条回答
  •  我在风中等你
    2020-11-27 15:29

    Focusing on one of the accepted answer's jQuery solutions, $.getScript() is an .ajax() request in disguise. It allows to execute other function on success by adding a second parameter:

    $.getScript(url, function() {console.log('loaded script!')})
    

    Or on the request's handlers themselves, i.e. success (.done() - script was loaded) or failure (.fail()):

    $.getScript(
        "https://code.jquery.com/color/jquery.color.js",
        () => console.log('loaded script!')
      ).done((script,textStatus ) => {
        console.log( textStatus );
        $(".block").animate({backgroundColor: "green"}, 1000);
      }).fail(( jqxhr, settings, exception ) => {
        console.log(exception + ': ' + jqxhr.status);
      }
    );
    .block {background-color: blue;width: 50vw;height: 50vh;margin: 1rem;}
    
    

提交回复
热议问题