Can you explain the logic of the function call on completion of asynchronous download of an external script?

Good evening, community.

Very often, when an external script is loaded asynchronously, for proper function call on the page uses a similar design:
(function(w, n) {
 w[n] = w[n] || [];
w[n].push({

 // some parameters

})(window, 'nezaniatosti');

Can you tell me how does that work?
March 23rd 20 at 18:48
1 answer
March 23rd 20 at 18:50
Solution
Not found, is formed. I'll try to explain how I understand this code.

During the execution of the code is unknown, it is determined whether the global object. From global needs to be a method push()that accepts a bundle of new options. But we are ready for both options: Purim or cool an object, or an empty array.

After loading a script that looks empty if a global property for which it applies. If not empty - the data accumulated there for him and he writes them himself where necessary during initialization. Something like this:
(function(w, n) {
 w[n] = w[n] || [];
 w[n].push({a: "A", b: "B"});
})(window, 'tosterQuery');



// in script loaded later
(function(w, n) {
 // do not overwrite object. Only if empty or an array.
 if (w[n] && !Array.isArray(w[n])) return;

 function f() {
 const data = w[n] || [];
 // define your push with a blackjack
 this.push = function(x) {return data.push(x);}
 this.getData = function() {return data;}
}

 w[n] = new f(); // hold global property
})(window, 'tosterQuery');

tosterQuery.getData(); // [{"a":"A","b":"B"}]
tosterQuery.push({z:"Z"});
tosterQuery.getData(); // [{"a":"A","b":"B"}, {"z":"Z"}]
Thank you, my friend, will be helped to understand. So, if you want another example, maybe someone can help. Often this is used to render a widget in the website and then the example will be something like this:

(function(w, n) {
 w[n] = w[n] || [];
 w[n].push({itemId: "1"});
})(window, 'superItemWidget');



// script is loaded asynchronously (or just later)

// A hypothetical function responsible for rendering the widget
const renderItem = (option) => {
 console.log(option.itemId + 'is rendered');
}

(function(w, n) {
 // if you already have in the space of the objects to render, called the render them
 if (w[n]) {
 w[n].forEach((option) => {
renderItem(option);
});
 } 

 // For add after downloading hang the render on push
 w[n] = new function () {
 this.push = function(option) {
renderItem(option);
}
}
})(window, 'superItemWidget');

// Page code that is processed after loading the external script:
(function(w, n) {
 w[n] = w[n] || [];
 w[n].push({itemId: "2"});
})(window, 'superItemWidget');
- Julie.Schumm6 commented on March 23rd 20 at 18:53

Find more questions by tags JavaScript