D
D
DenimTornado2014-09-22 18:06:40
JavaScript
DenimTornado, 2014-09-22 18:06:40

How does VK.api work?

Interested in the moment of initialization. There is an api, it can only be accessed when all modules are loaded. Loading modules is sticking scripts into the header. Hence the question - how can you understand that all the scripts are inserted and you can pull the api?

//Сам инит
My.init = function (callback) {
  if (My.isFunc(callback)) callback();
};

//Вызов апи, когда произошёл инит 
My.init(function(){
   My.api('user', {uid:2}, function(data) {
       console.log(data);
   });
});

//Загрузка модулей
My.loadModule = function (src, callback, appendTo) {
  var script = document.createElement('script');

  if (!appendTo) {
    appendTo = document.getElementsByTagName('head')[0];
  }

  if (script.readyState && !script.onload) {
    // IE, Opera
    script.onreadystatechange = function () {
      if (script.readyState == "loaded" || script.readyState == "complete") {
        script.onreadystatechange = null;
        callback();
      }
    }
  }
  else {
    script.onload = callback;
  }

  script.src = My.domain + '/js/modules/' + src + '.js';
  appendTo.appendChild(script);
};

Here is such a code, in the modules folder there are modules, respectively. How to determine that all scripts are in the header and give the green light to the execution of functions inside My.init(function(){}?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
ArthurSupertramp, 2014-09-22
@ArthurSupertramp

habrahabr.ru/post/182310
As far as I understand, if you connect scripts to work with api after connecting all modules, your script will not start until those above are downloaded and executed. So some kind of callback is not needed in this situation.

T
Testtest132, 2014-09-22
@Testtest132

Why not write a class for loading scripts, or take something ready.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question