简体   繁体   中英

Include a javascript library for calculation

I want to do something very simple in javascript. I have a main.js file which needs to call a calculation method in math.js.

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

If not, would I need to do some overkilled hack like I read here How do I include a JavaScript file in another JavaScript file? or even worse because I can't even see in that link how dependency is actually taken into account.

Update: Why can't I do like what Dashcode seems to do How can I add my library to be loaded Dashcode parts ie just use document.write('...')? Is in fact document.write robust enough on a very slow connection if the library was bigger than main.js ?

Set a variable in math.js and proove in main.js if this variable exist.

var mathLoaded = true;

in main.js:

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

Edit:

Now you can start an wait function, until it is loaded:

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

window.setTimeout(function() { wait(); }, 0);

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

also, JS gets loaded and parsed top-bottom. whichever comes first in the source gets fetched first and parsed first (but it doesn't guarantee order as servers for some files may be slow). that's why it's recommended that if you use libraries and toolkits (like jQuery and others), they should be loaded before anything else.

No you are not. The files can be loaded in any order. You typically want to call your initial code from the documents load event. That even it triggered once all the files needed for the page are loaded.

Why not use window.onload ?

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

or get really fancy with a cross-browser addEvent function?

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 attaches functions to events properly...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM