简体   繁体   English

准备好文档后如何执行所需的代码

[英]How to execute required code when document was ready

main.js main.js

require.config({
    paths: {
        'jq': 'jquery.min',
        'init': 'init'
    },
    shim: {
        'init': ['jq']
    }
});
requirejs(['init']);

init.js init.js

requirejs(['func'], function(func) {
    $(function() {
        // Do something when document is ready
        func.doSomething();
    });
});

func.js func.js

define(function() {
    var box = $('.box');

    return {
        doSomething: function() {
            // Do something;
        }
    }
});

I required fun.js when use init.js , which means if I set param like var box = $('.box') in the beginning might not get the dom because it's not created, I know I can declare it in doSomthing function, but is it possible to declare it to global and let other function in func.js can reuse it and make sure it happened after dom is ready. 我在使用fun.js时需要init.js ,这意味着如果我在一开始就像var box = $('.box')那样设置参数,可能因为未创建而无法获得dom,我知道我可以在doSomthing函数中声明它,但是可以将其声明为global并让func.js其他函数重用它并确保它在dom准备就绪后发生。

You should make your module be dependent on the DOM being ready. 您应该使模块依赖于准备就绪的DOM。 You do this by using the domReady plugin . 您可以使用domReady插件来执行此操作。 Define func.js like this: 像这样定义func.js

define(['domReady!'], function() {
    var box = $('.box');
    //...
});

The exclamation point is not a typo. 感叹号不是错字。 By requiring domReady! 通过要求domReady! you are asking it to work like a plugin, rather than a regular module. 您要求它像插件一样工作,而不是常规模块。 This dependency won't resolve until the DOM is ready. 在DOM准备就绪之前,这种依赖性将无法解决。 Make sure to read the documentation of domReady . 确保阅读domReady的文档。 In particular you may need to increase the waitSeconds configuration option. 特别是,您可能需要增加waitSeconds配置选项。

To execute code after the document is ready, I suggest using an IIFE (Immediately-Invoked Function Expression). 要在文档准备好后执行代码,建议使用IIFE(立即调用函数表达式)。

(function ($) {
    var box = $('.box');
}) (jQuery);

To declare a global variable in javascript, you can attach it to the "window" object. 要在javascript中声明全局变量,可以将其附加到“窗口”对象。

(function ($) {
    window.box = $('.box');
}) (jQuery);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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