2

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

elkebirmed
  • 2,247
  • 6
  • 24
  • 35

2 Answers2

2

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

Macha
  • 14,366
  • 14
  • 57
  • 69
  • @elkebirmed It appears that the promise resolves when the script is downloaded, and not when it executes, even for dataType: "script" – Macha Jan 18 '16 at 23:13
1

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(...)
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
vittore
  • 17,449
  • 6
  • 44
  • 82
  • not true about $.when...in fact it does not accept array and have to use `apply()` if it is array – charlietfl Jan 17 '16 at 18:05
  • 2
    $.when accept one argument which is array: The docs seem to indicate otherwise, see this line: `$.when( d1, d2 )` on this page https://api.jquery.com/jQuery.when/ – Macha Jan 17 '16 at 18:07
  • `{"readyState":1}` is returned by using `console.log(JSON.stringify(_$));` which is a variable holding `_$ = $.ajax......` – elkebirmed Jan 17 '16 at 18:31
  • JSON.stringify does not include methods, which are the important part of promises. It'll have a number of methods such as .then etc. – Macha Jan 18 '16 at 23:12