Answer the question
In order to leave comments, you need to log in
How to write your own require method?
Hello, tell me please.
The task is as follows: I want to write my own method - require , which should load js files.
That is, it should look something like this:
// file2.js
require('file1.js');
// и дальше используем св-ва и методы из file1.js
function require(src) {
// динамически создаем тег скрип, в который будем передавать src файла
}
Answer the question
In order to leave comments, you need to log in
Yes, it's quite possible to create a script tag dynamically, etc. (RequireJS does just that). But there will be pitfalls, especially if you need to support older browsers. Plus, the issue of assembly remains - since you are worried about the size, it means that you will not upload a bunch of individual files for sale, but will glue them together, but how to determine the order?
For RequireJS there is almond , on the prod the overhead will be only 1 kb - not so much, huh?
Another option - Browserify, overhead - generally about 500 bytes, much less? The disadvantage, of course, is that a build step is needed, but many do not mind, you should try it too.
not quite a name, it's rather a virtual path ( require('../model/order', ... )
), which resolves to a physical one, based on the project root, the path to the current module, and aliases and shims, if they are specified in the config.
You can try promises :
function load_script_promise(url){
return new Promise(function(resolve, reject){
var head = document.getElementsByTagName('head')[0]
var script = document.createElement('script')
script.type = 'text/javascript'
script.addEventListener('load', function(){
this.removeEventListener('load', arguments.callee)
resolve(script)
})
script.src = url
head.appendChild(script);
})
}
Promise.all([
load_script_promise("some1.js"),
load_script_promise("some2.js")
]).then(alert)
There are two options. First: load the contents of the script via ajax and execute it via eval, functions and objects will be available immediately after eval. Second: as you wrote, create a script element. In this case, the browser will load this script asynchronously and you will not be able to use the functions and objects from the loaded script immediately after creating the element.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question