Skip to content
Fix Code Error

$(document).ready equivalent without jQuery

March 13, 2021 by Code Error
Posted By: Anonymous

I have a script that uses $(document).ready, but it doesn’t use anything else from jQuery. I’d like to lighten it up by removing the jQuery dependency.

How can I implement my own $(document).ready functionality without using jQuery? I know that using window.onload will not be the same, as window.onload fires after all images, frames, etc. have been loaded.

Solution

There is a standards based replacement,DOMContentLoaded that is supported by over 98% of browsers, though not IE8:

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

jQuery’s native function is much more complicated than just window.onload, as depicted below.

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            jQuery.ready();
        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                jQuery.ready();
            }
        });

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && window == window.top ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch( error ) {
                setTimeout( arguments.callee, 0 );
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        })();
    }

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );
}
Answered By: Anonymous

Related Articles

  • npm install error in vue
  • Maven2: Missing artifact but jars are in place
  • Error: container has not been made global - how to solve?
  • Pure JavaScript equivalent of jQuery's $.ready() -…
  • UnsatisfiedDependencyException: Error creating bean…
  • What does do?
  • Vuetify grid system row management
  • Where do I find the current C or C++ standard documents?
  • Spring data jpa- No bean named…
  • Tomcat 7 "SEVERE: A child container failed during start"
  • After a little scroll, the sticky navbar just is not…
  • Spring Boot - Cannot determine embedded database…
  • adding to window.onload event?
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Error: undefined Unable to resolve module
  • Which maven dependencies to include for spring 3.0?
  • How to make the overflow CSS property work with…
  • Maven Could not resolve dependencies, artifacts…
  • jQuery Mobile: document ready vs. page events
  • How can I mock an ES6 module import using Jest?
  • Testing aurelia customElement with bindable and dependencies
  • Error creating bean with name 'entityManagerFactory'…
  • Difference between variable declaration syntaxes in…
  • How can I quantify difference between two images?
  • Eclipse Spring Boot need declare Maven dependency explicitly
  • Custom date picker in Vuetify
  • The superclass "javax.servlet.http.HttpServlet" was…
  • addEventListener vs onclick
  • Disable Logback in SpringBoot
  • Javascript and SVG - move element with offset
  • sql query to find priority jobs
  • Why does C++ code for testing the Collatz conjecture…
  • A fatal error has been detected by the Java Runtime…
  • data.table vs dplyr: can one do something well the…
  • java.lang.ClassNotFoundException:…
  • Switch between two frames in tkinter
  • Exception in thread "JobGenerator"…
  • Exception in thread "main"…
  • Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap
  • How do I include a JavaScript file in another…
  • How to observe embedded arrays in Ember objects?
  • Does Ember.js support IE6?
  • Error Message : Cannot find or open the PDB file
  • Include resource directory into Quarkus target output
  • Logging best practices
  • Adding eventListener to blur event on custom component?
  • The definitive guide to form-based website authentication
  • Use latest version of Internet Explorer in the…
  • How do I keep only the first map and when the game…
  • Vue, Vuetify - Reduce space between buttons in toolbar
  • Programmatically Lighten or Darken a hex color (or…
  • Aurelia UX showcase app fails to load
  • Why does jQuery or a DOM method such as…
  • How do i arrange images inside a div?
  • VueJS masonry layout
  • window.onload vs document.onload
  • How to remove old and unused Docker images
  • setTimeout function not working : javascript
  • Visual Studio debugging/loading very slow
  • How do you cache an image in Javascript
  • Comparison between Corona, Phonegap, Titanium
  • How to filter a RecyclerView with a SearchView
  • Mobile browsers add a gap at the end of final…
  • For-each over an array in JavaScript
  • Am I paranoid? "Brutally" big Polymer website after…
  • How to detect if multiple keys are pressed at once…
  • Smart way to truncate long strings
  • Polymer paper-dialog: how can I know when an…
  • Load and execution sequence of a web page?
  • How can I add multiple images along with other input…
  • tkinter problem in displaying two frames using tkraise
  • What are the different usecases of PNG vs. GIF vs.…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • x264 / libx264 : Can only one I/P frame to be used…
  • How to download and save an image in Android
  • What are the undocumented features and limitations…
  • My DIV elements go diagonal instead of horizontal
  • JavaScript gives NaN error on the page but variable…
  • Trouble with Next js + Express deployment using Zeit Now
  • disabling spring security in spring boot app
  • What is an application binary interface (ABI)?
  • Aurelia, webpack and dynamic reference to images
  • What does AngularJS do better than jQuery?
  • how to use canvas in JavaScript flappy bird code
  • flutter - add network images in a pdf while creating…
  • How to download javafx libraries for each operating…
  • Vue&TypeScript: how to avoid error TS2345 when…
  • How do I trigger a loading event after the window…
  • Polymer 1.0 Trying to make a splitter which works…
  • How to submit Polymer forms to PHP and display response
  • Vue.js, How to get a list of latitude and longitude…
  • Java.lang.NoClassDefFoundError:…
  • YouTube iframe API: how do I control an iframe…
  • Change the background color of a list item in Vuetify
  • "Thinking in AngularJS" if I have a jQuery background?
  • Next.js - Warning: Prop `dangerouslySetInnerHTML`…
  • .gitignore and "The following untracked working tree…
  • Setting equal heights for div's with jQuery
  • NextJS: Images loaded from cache don't trigger the…
  • Attach a body onload event with JS

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Behaviour of increment and decrement operators in Python

Next Post:

Redirect all output to file in Bash

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error