Toni Michel Caubet
Toni Michel Caubet

Reputation: 20183

Dynamically add .js file, how to know when it's ready?

In order to only load the jquery swipe script in touch devices, I am detecting it with modernizer and appending the script if is touch, like this:

/**/
if ( modernizer.touch ) {
    var js = jQuery("<script>");
    css.attr({
      type:  "text/css",
      src: base_url + "/js/jquery-touch-swipe.js?p1"
    });
    $("head").append(css);
    $this.swipe( function( e, dx, dy ){
        if( dx < 0 ){
            $this.find('.next').click();
        } else {
            $this.find('.prev').click();
        }
    });
}

The problem is that right after, the function swipe isn't ready yet. I could use a setTimeout but I couldn't be sure either,

How can I make sure the appended script is ready?

I tried like this:

    if ( modernizer.touch ) {
        var js = jQuery("<script>");
        css.attr({
          type:  "text/css",
          src: base_url + "/js/jquery-touch-swipe.js?p1",
          id: 'swipe'
        });
        $("head").append(css);
        $('#swipe').load(function() {
            $this.swipe( function( e, dx, dy ){
                if( dx < 0 ){
                    $this.find('.next').click();
                } else {
                    $this.find('.prev').click();
                }
            });
        });


}

But with no success

Upvotes: 0

Views: 48

Answers (1)

Satpal
Satpal

Reputation: 133453

You can use $.getScript and the use its success callback function which will execute once script is loaded but not necessarily executed.

if (Modernizr.touch) {
    $.getScript(base_url + "/js/jquery-touch-swipe.js?p1", function () {
        //Operation which you want to perform
    });
}

Upvotes: 3

Related Questions