Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage dependencies in JavaScript?

I have scripts that needs to wait for certain conditions to be met before they run - for example wait for another script to be loaded, or wait for a data object to be created.

How can I manage such dependencies? The only way I can think of is to use setTimeout to loop in short intervals and check the existence of functions or objects. Is there a better way?

And if setTimeout is the only choice, what is a reasonable time interval to poll my page? 50 ms, 100 ms?

[Edit] some of my scripts collect data, either from the page itself or from Web services, sometimes from a combination of multiple sources. The data can be ready anytime, either before or after the page has loaded. Other scripts render the data (for example to build charts).

[update] thanks for the useful answers. I agree that I shouldn't reinvent the wheel, but if I use a library, at least I'd like to understand the logic behind (is it just a fancy timeout?) to try and anticipate the performance impact on my page.

like image 771
Christophe Avatar asked Nov 03 '25 11:11

Christophe


2 Answers

You could have a function call like loaded(xyz); at the end of the scripts that are being loaded. This function would be defined elsewhere and set up to call registered callbacks based on the value of xyz. xyzcan be anything, a simple string to identify the script, or a complex object or function or whatever.


Or just use jQuery.getScript(url [, success(data, textStatus)] ).

like image 198
Supr Avatar answered Nov 05 '25 14:11

Supr


For scripts that have dependencies on each other, use a module system like RequireJS.

For loading data remotely, use a callback, e.g.

$.get("/some/data", "json").then(function (data) {
    // now i've got my data; no polling needed.
});

Here's an example of these two in combination:

// renderer.js
define(function (require, exports, module) {
    exports.render = function (data, element) {
        // obviously more sophisticated in the real world.
        element.innerText = JSON.stringify(data);
    };
});

// main.js
define(function (require, exports, module) {
    var renderer = require("./renderer");

    $(function () {
        var elToRenderInto = document.getElementById("#render-here");

        $("#fetch-and-render-button").on("click", function () {
            $.get("/some/data", "json").then(function (data) {
                renderer.render(data, elToRenderTo);
            });
        });
    });
});
like image 41
Domenic Avatar answered Nov 05 '25 15:11

Domenic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!