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

2
  • FYI...there is shortcut $.getScript() you could also use Commented Jan 17, 2016 at 18:13
  • with $.getScript() you can't cache the sctipt Commented Jan 17, 2016 at 18:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@elkebirmed It appears that the promise resolves when the script is downloaded, and not when it executes, even for dataType: "script"
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(...)

4 Comments

not true about $.when...in fact it does not accept array and have to use apply() if it is array
$.when accept one argument which is array: The docs seem to indicate otherwise, see this line: $.when( d1, d2 ) on this page api.jquery.com/jQuery.when
{"readyState":1} is returned by using console.log(JSON.stringify(_$)); which is a variable holding _$ = $.ajax......
JSON.stringify does not include methods, which are the important part of promises. It'll have a number of methods such as .then etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.