📜 ⬆️ ⬇️

JavaScript loader without define

Hi Habr!

Everyone knows the solution to the problem of loading scripts.
For example Curl.JS, Require.JS, + popular frameworks can do this too.

MAIN UPDATE: Everything was discussed in the comments. Thank you azproduction and nuit for ideological comments, and ainu for moral support.
')
From the comments it is clear that 100% is better to use LMD , because there everything is the same as is told here, only there is dependency accounting, cache, etc. And yes, it was invented much earlier, i.e. was first!

What is LMD : read respected azproduction .

Under the cut there is a code that can be used for informational purposes to answer the question of why MAIN UPDATE was written, that is, why you should use LMD instead of what’s under the cut.
It is also important that the 'with' operator is currently Deprecated .



All this is written with reference to the link .

Only the bootloader code is given, no additional aspects that are included in the LMD - no.

UPD: done in an attempt to implement in the browser how mozIJSSubScriptLoader and / or Components.utils.import for Firefox extensions work.

Ie, load the script, while redefining its scope.

An example .

A couple of links to the initial source: One and Two

The final code for the script loader as a method for jQuery:

(function( jQuery, undefined ){ jQuery.loadSubScript = function( url, scope, thisName, returnCallback ){ //    scope    var scope = scope || window; //  var thisName = thisName || window; $.ajax( { url: url , type: 'GET' , dataType: 'text' , success: function( data ){ try{ //   ,    with var fns = new Function( 'with( this ){ return ' + Function.apply( null, [ data ] ) + '; }' ); //    with fns = fns.call( scope ); //    this var turn = fns.call( thisName ); //    callback,    returnCallback && returnCallback( turn ); }catch(e){ alert(e); } } , error: function( jqXHR, textStatus, errorThrown ){ alert('Loader Error:\n' + errorThrown ); } } ); }; })( jQuery ); 


There is also NOT a Plugin in which the noConflict method is implemented, which allows to remove the loader code from the window (jQuery is still used for $ .ajax).

What can be obtained using this code:



Of course, if something will carry a var , then it will be inside the created circuit. Without var, as it should be, it will go to window. What are the methods of the object passed into the scope will be available without a dot. With this - everything is as usual, in case of its substitution.

Restrictions: local files in Google Chrome and Opera.
For Chrome, it is treated by running with the key: --allow-file-access-from-files.

But it is better to use LMD.

Use on health!

GIT Link

Best Regards!

PS: I do not know which license to choose, probably MIT + GPLv3.

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


All Articles