Providing a callback for async script

I need to load a third-party script that is not critical for displaying the body (say, for simplicity, that it adds a red background to the ".red" divs).

<script src="redify.js" async defer></script>

I need to execute function myRedify(){ $(".red").redify(); }after loading the script.

The script is huge and takes a lot of time (say 3 seconds) to load, but as soon as I finish, I need to see my divs turn .redred.

<script src="redify.js" async defer onload="myRedify()"></script>

Is this the recommended way to do this?

Notes

  • redify.js is a third-party script that I cannot change
  • I do not mind if the divs did not turn red immediately, but after a delay (when the script loads, 3 seconds - ok)
+4
source share
1

, merrit. ? . :

  • : refify script
  • : HTML, ,
  • , (: blueify.js), .

myRedify. , require:

var libraries = {
    redify: "redify.js",
    blueify: "blueify.js"
};
var lib_bookkeep = {};

function require(library_name, callback) {
    if (lib_bookkeep[library_name]) {
         if (lib_bookkeep[library_name].status === "loaded") {
             callback();
         } else {
             lib_bookkeep[library_name].elem.addEventListener("load", callback);
         }
    } else {
        var script = document.createElement("script");
        script.src = libraries[library_name];
        script.addEventListener("load", function () {
            lib_bookkeep[library_name].status = "loaded";
        });
        script.addEventListener("load", callback);
        document.head.appendChild(script);
        lib_bookkeep[library_name] = {
            elem: script
            status: "loading"
        }
    }
}

require("redify", function () {
    $(".red").redify();
});

require("redify", function () {
    $(".also-red").redify();
});

require("blueify", function () {
    $(".blue").redify();
});
require("blueify", function () {
    require("redify", function () {
        $(".purple").redify().blueify();
    });
});

, , . , . , , , , , , , asynch/defer onload.

0

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


All Articles