Enable javascript library for calculation

I want to do something very simple in javascript. I have a main.js file that needs to be called by the calculation method in math.js.

If I include these two files with a script tag in index.html, first math.js and then main.js, am I sure that math.js will be loaded before I can use it in main.js?

If not, I need to do some kind of crowded hack, as I read here How do I include a JavaScript file in another JavaScript file? or worse, because I may not even see in this link how much the dependency is actually taken into account.

Update: why can't I do what Dashcode seems to be doing How to add my library to load parts of Dashcode , i.e. just use document.write ('...')? Actually document.write is simple enough in a very slow connection, if the library was larger than main.js?

+4
source share
4 answers

Set the variable in math.js and proove in main.js if this variable exists.

var mathLoaded = true; 

in main.js:

 function loaded() { return ((typeof mathLoaded) !== 'undefined'); } 

Edit:

Now you can run the wait function until it is loaded:

 function wait() { if(loaded()) { //doSomething(); } else { window.setTimeout(function() { wait(); }, 0); } } window.setTimeout(function() { wait(); }, 0); 
+4
source

you can take a look at RequireJS to make sure dependencies are loaded

also, JS is loaded and parsed by the top bottom. depending on what comes first in the source, it first gets the selection and parses it first (but this does not guarantee order, since the servers for some files may be slow). why he recommended that when using libraries and toolkits (e.g. jQuery and others) they should be loaded first.

+1
source

No no. Files can be downloaded in any order. Usually you want to call your source code from a load document. It even worked after loading all the files needed for the page.

+1
source

Why not use window.onload ?

 window.onload = function () { //your code here. } 

or really come up with the addEvent cross-browser addEvent ?

 var libJS = { addEvent: function (obj, type, fn) { if (obj.addEventListener) { obj.addEventListener(type, fn, false); return true; } else if (obj.attachEvent) { obj['e' + type + fn] = fn; obj[type + fn] = function () { obj['e' + type + fn](window.event); } var r = obj.attachEvent('on' + type, obj[type + fn]); return r; } else { obj['on' + type] = fn; return true; } } } 

which correctly binds functions to events ...

 libJS.addEvent(window, 'load', someMainJsFunction); //add to window.onload 
+1
source

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


All Articles