仅在DOM加载功能后才替换jquery的运行

时间:2012-02-23 07:11:40

标签: javascript jquery

我试图消除对jQuery的依赖。我从underscore.js中偷了我需要的几个函数,但是仍然需要在以与jQuery相同的方式加载DOM之后运行我的代码

原始

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

所需

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

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

2 个答案:

答案 0 :(得分: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!' );
});

答案 1 :(得分:0)

我会在这里留下我的问题,因为我在搜索堆栈溢出后询问了以获得答案,但是我猜测了搜索条件。我希望其他人会觉得这个答案很有用。

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

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

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

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

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

它也可以在桌面浏览器上运行,显然已经在所有主要浏览器上进行了测试。 FF&lt; 3.6的详细信息和修正可在此处找到:http://dustindiaz.com/smallest-domready-ever