browserify and document ready?

后端 未结 5 1018
慢半拍i
慢半拍i 2021-02-08 00:28

I\'m struggling with using Browserify and document ready events. How do I craft a module that exports content only available after the document ready event has fired? How do I

5条回答
  •  灰色年华
    2021-02-08 01:18

    Try this:

    var domready = require("domready");
    
    domready(function () {
        exports.something = /* whatever you want */
    });
    

    You'll need to download the domready package:

    npm install domready
    

    Then just use browserify:

    browserify input.js -o output.js
    

    Yes. It's that simple.


    Consider that we have two files: library.js and main.js.

    // library.js
    
    var domready = require("domready");
    
    domready(function () {
        exports.test = "Hello World!";
    });
    
    // main.js
    
    var library = require("./library");
    var domready = require("domready");
    
    domready(function () {
        alert(library.test);
    });
    

    As long as you require your library before you register your main domready function you should be able to use your library seamlessly.


    Sometimes you may wish to set module.exports to a function. In that case you can use the following hack:

    // library.js
    
    var domready = require("domready");
    
    module.exports = function () {
        return exports._call.apply(this, arguments);
    };
    
    domready(function () {
        exports._call = function () {
            alert("Hello World!");
        };
    });
    
    // main.js
    
    var library = require("./library");
    var domready = require("domready");
    
    domready(function () {
        library();
    });
    

    Note that the _call property is not in any way special.

提交回复
热议问题