Rubén_ic Rubén_ic - 20 days ago 7
Javascript Question

DOMContentLoaded not working like $(document).ready() in a simple scenario

On the main file of my webpack assets bundle for an Angular2 app, I'm not being able to listen for the


The file just has the following lines:

// styles
const bootstrapLoader = require('bootstrap-loader');
const styleScss = require('./main.scss');
// scripts
const $ = require('jquery');
const jQueryUjs = require('jquery-ujs');
const coreJS = require('core-js');
const zoneJS = require('zone.js');
const reflectMetadata = require('reflect-metadata');
const myAngularApp = require('./main.ts');

document.addEventListener('DOMContentLoaded', function () {

On the other hand, if I use jQuery, it works perfectly, id est, changing the last three lines with the following ones:

$(document).ready(function() {

This looks so basic, but I don't understand why the plain javascript version of the document ready is not working here...

Many thanks!


It's not the same

Most browsers provide similar functionality in the form of a DOMContentLoaded event. However, jQuery's .ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls .ready( handler ), the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.