elkebirmed
elkebirmed

Reputation: 2357

Why jquery pjax is not defined when using jquery ajax load

Why jquery pjax is not defined in the js file, but it's defined in the console if i type $.pjax

function loadScript(url, callback) {
  callback = (typeof callback != 'undefined') ? callback : {};
  $.ajax({
    type: "GET",
    url: url,
    success: callback,
    dataType: "script",
    cache: true,
  });
}

$('document').ready(function() {
  $.when(
    loadScript('//cdnjs.cloudflare.com/ajax/libs/codemirror/5.10.0/codemirror.min.js'),
    loadScript('//cdnjs.cloudflare.com/ajax/libs/jquery.pjax/1.9.6/jquery.pjax.min.js')
  ).done(function() {
    $('.loading').hide().next().css({
      'visibility': 'visible',
      'overflow-y': 'auto',
    });
    console.log($.pjax() + ' ...');
  });

});

it console this error: Uncaught TypeError: $.pjax is not a function

Upvotes: 2

Views: 4139

Answers (2)

vittore
vittore

Reputation: 17589

You have two issues here.

  • You have to return a promise that is returned by $.ajax

  • $.when accept one argument which is array

ie

function loadScript(...) {
 ... 
 return $.ajax
}

$.when([loadScript('a'), loadScript('b')]).then(...)

Upvotes: 1

Macha
Macha

Reputation: 14664

Your loadScript function does not return a promise, so from the point of view of $.when, your scripts load immediately, which is not the reality.

Try change the line :

$.ajax({
// ...
})

to

return $.ajax({
// ...
});

so you return a promise for $.when

Upvotes: 2

Related Questions