thorstorm thorstorm - 3 months ago 10
Javascript Question

requirejs unexpected behaviour

// conifg.js
require.config({
paths: {
'main': 'main',
'socketio': './libs/socket.io/socket.io',
'plotly': './libs/plotly/plotly-latest.min',
'renderDataToPlotly': './scripts/renderDataToPlotly',
'jquery': './libs/jquery/jquery-2.1.4.min',
'jqueryUI': './libs/jquery/jquery-ui-1.11.4.custom/jquery-ui.min',
'sliders': './scripts/sliders',
'makePlotlyWindowResponsive': './scripts/makePlotlyWindowResponsive'
},
shim: {
'jqueryUI': ['jquery']
}
});

require(['main']);

// main.js
define([
'jquery',
'jqueryUI',
'socketio',
'sliders',
'makePlotlyWindowResponsive',
'renderDataToPlotly'
],
function($, ui, io, sliders, makePlotlyWindowResponsive, renderDataToPlotly) {
//
}
);

// renderDataToPlotly.js and makePlotlyWindowResponsive.js
define(['plotly'], function() {

});


When I load the page I get this load order:
enter image description here
As you can see,
makePlotlyWindowResponsive.js
(1, on image) loads before
plotly-latest.min.js
(2, on image). As I understand requirejs mechanics, I would spect a
Plotly is not defined
error on
makePlotlyWindowResponsive.js
, but I'm not getting any. Everything works.

I want to understand requirejs and how it works.

Question 1: How there is not an error?

Question 2: That means that, despite load order, there is no error if files are loaded before page is fully loaded?

Thanks for your time!

Answer

When requirejs receives a script from the network, it runs that script. the require (or define?) function says "download these other scripts, then run them, and once you've got all their return values, run this function". So it waits for the other scripts to load and return their values before calling the function in this one. In short, the order in which they load may not be the same as the order in which their functions run.