How to load a script synchronously with RequireJS

I am using RequireJS in ASP.NET. There is a user control that contains a script file and registers the launch of a script to initialize itself. Here is the generated code:

<script src="script/UserControls/myctrl.js" type="text/javascript"></script> 

...

 <script type="text/javascript"> function myCtrl1_init() { // initialize control // *JS ERROR* because myctrl.js hasn't run yet Sys.Application.remove_load(myCtrl1_init); } Sys.Application.add_load(myCtrl1_init); </script> 

The file myctrl.js looks something like this:

 require(['script/dep1', 'script/dep2'], function(dep1, dep2) { MyCtrl = function () { }; MyCtrl.init = function(id) { dep1.doSomething(); } }; 

Thus, the problem is that the script is run before the myctrl.js file was able to run. Currently, the call request uses a callback function, which obviously does not work until a later version, and this is the problem ... the script returns, and the browser continues to run the script before MyCtrl was created.

I tried just calling require(['script/dep1', 'script/dep2']); at the top of the file, but this does not block, and the script fails because the dependencies are not yet loaded. Dependencies are, by the way, modules. they use define() .

Is there a way to download a script file synchronously with RequireJS? The API documentation says that β€œUsing RequireJS in a server-side JavaScript with synchronous loading should be as simple as redefining require.load (),” but I have no idea what that means.

Any suggestions?

+4
source share
1 answer

I assume the script tag for require.js is above the content you specified. If so, then I would convert myctrl.js to a module (use "define ('myctrl', ....) instead of" require (.. "inside it), and then do something like this in the inline content of the script tag :

 <script type="text/javascript"> require(["myctrl"], function () { function myCtrl1_init() { // initialize control // *JS ERROR* because myctrl.js hasn't run yet Sys.Application.remove_load(myCtrl1_init); } Sys.Application.add_load(myCtrl1_init); }); </script> 

I am not familiar with ASP.NET, so I'm not sure what to make these Sys.Application calls in a callback that can fire after DOMContentLoaded, but this is a general idea.

It is not possible to synchronously load a script in a browser with RequireJS, you must use the callback method as described above. The information require.load () was intended for developers who want RequireJS adapters to run in synchronization environments (mostly not in the JS browser).

+2
source

Source: https://habr.com/ru/post/1342601/


All Articles