【问题标题】:replace jquery's run only after DOM is loaded functionality仅在加载 DOM 功能后替换 jquery 的运行
【发布时间】:2012-02-23 16:25:17
【问题描述】:

我正在尝试消除对 jQuery 的依赖。我从 underscore.js 中窃取了一些我需要的函数,但在 DOM 加载后仍然需要我的代码以与 jQuery 相同的方式运行

原创

$(function(){
  // all my code
})

想要的

var afterload = function(content){
    // what goes here..?
}

afterload(function(){
    // my code that should run after the DOM is loaded
})

【问题讨论】:

  • 如果您查看 jQuery 源代码,检测文档准备就绪比您想象的要困难得多...
  • 我认为这可能会对您有所帮助stackoverflow.com/questions/799981/…
  • 以及this。对此已有几个问题。

标签: javascript jquery


【解决方案1】:

https://github.com/freelancephp/DOMReady 有一个很好的解决方案,

这是一个脚本

/**
 * DOMReady
 *
 * @fileOverview
 *    Cross browser object to attach functions that will be called
 *    immediatly when the DOM is ready.
 *    Released under MIT license.
 * @version 2.0.0
 * @author Victor Villaverde Laan
 * @link http://www.freelancephp.net/domready-javascript-object-cross-browser/
 * @link https://github.com/freelancephp/DOMReady
 */

/**
 * @namespace DOMReady
 */
var DOMReady = (function () {

    // Private vars
    var fns = [],
        isReady = false,
        errorHandler = null,
        run = function ( fn, args ) {
            try {
                // call function
                fn.apply( this, args || [] );
            } catch( err ) {
                // error occured while executing function
                if ( errorHandler )
                    errorHandler.call( this, err );
            }
        },
        ready = function () {
            isReady = true;

            // call all registered functions
            for ( var x = 0; x < fns.length; x++ )
                run( fns[x].fn, fns[x].args || [] );

            // clear handlers
            fns = [];
        };

    /**
     * Set error handler
     * @static
     * @param {Function} fn
     * @return {DOMReady} For chaining
     */
    this.setOnError = function ( fn ) {
        errorHandler = fn;

        // return this for chaining
        return this;
    };

    /**
     * Add code or function to execute when the DOM is ready
     * @static
     * @param {Function} fn
     * @param {Array} args Arguments will be passed on when calling function
     * @return {DOMReady} For chaining
     */
    this.add = function ( fn, args ) {
        // call imediately when DOM is already ready
        if ( isReady ) {
            run( fn, args );
        } else {
            // add to the list
            fns[fns.length] = {
                fn: fn,
                args: args
            };
        }

        // return this for chaining
        return this;
    };

    // for all browsers except IE
    if ( window.addEventListener ) {
        document.addEventListener( 'DOMContentLoaded', function(){ ready(); }, false );
    } else {
        // for IE
        // code taken from http://ajaxian.com/archives/iecontentloaded-yet-another-domcontentloaded
        (function(){
            // check IE's proprietary DOM members
            if ( ! document.uniqueID && document.expando ) return;

            // you can create any tagName, even customTag like <document :ready />
            var tempNode = document.createElement( 'document:ready' );

            try {
                // see if it throws errors until after ondocumentready
                tempNode.doScroll( 'left' );

                // call ready
                ready();
            } catch ( err ) {
                setTimeout( arguments.callee, 0 );
            }
        })();
    }

    return this;

})();

你可以这样使用

DOMReady.add(function (){
    alert( 'DOM is ready!' );
});

【讨论】:

    【解决方案2】:

    我将把我的问题留在这里,因为我在 搜索堆栈溢出后询问了答案,但搜索了我猜想的令人费解的术语。我希望其他人会发现此答案有用。

    最初,我打算在功能上等同于 jQuery 解决方案,但不依赖 jQuery。事实证明这是非常庞大和复杂的......

    https://stackoverflow.com/a/7053197/665261

    然后我决定我想要一个简洁的解决方案,因为删除 jQuery 依赖的原因是为了让我的代码在低规格设备上加载得更快。

    我只针对 Android 移动设备,我最终使用了这个:

    function afterload(content){
      /in/.test(document.readyState)
      ? setTimeout(function(){ afterload(content) }, 9)
      : content()
    }
    

    它也应该在桌面浏览器上工作,显然在所有主要浏览器上都经过测试。可以在此处找到 FFhttp://dustindiaz.com/smallest-domready-ever

    【讨论】:

      猜你喜欢
      • 2011-08-10
      • 2017-01-04
      • 2011-12-13
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多