kubetail-org / loadjs

A tiny async loader / dependency manager for modern browsers (899 bytes)
MIT License
2.57k stars 149 forks source link

Is it possible to load JSON? #101

Closed migliori closed 4 years ago

migliori commented 4 years ago

Hi,

I can't figure out how to load a JSON file and access the JSON object, is it possible? Perhaps it would be interesting to be able to code something like this?:

loadjs(['json!/path/to/file.json'], function(obj) {
    /* file.json loaded as json */
    console.log(obj);
});
amorey commented 4 years ago

LoadJS uses the browser's built-in tags (<script>, <style>, <img>) to load files and as far I know you can't load JSON directly using those tags. However, you can use the jsonp method in conjunction with LoadJS if that's useful:

Client code:

window.callbackFn = function(json) {
  console.log(json);
}

loadjs('/server-endpoint', function() {
  // server has responded and callbackFn has been called
});

Server reponse:

callbackFn({
  mykey1: myval1,
  mykey2: myval2,
  ...
});
migliori commented 4 years ago

Thanks for your answer, in most cases it would be a good solution (unfortunately not for me, I'm inside a tinyMce plugin dialog iFrame with TypeScript, so I'll use XMLHttpRequest instead)