[JavaScript] jQuery document ready

Published on 2020-01-06 • Modified on 2020-01-06

This is a classic JavaScript snippet we all used at least once! There are several ways to achieve this, but I think the following code is the most readable. For those who don't know, some explanations. The code contained in this block will only be run when the page DOM (Document Object Model) has been loaded correctly (all content may not have been loaded yet, likes images). Check out the Stackoverflow link to have additional information. You can open your JavaScript console to verify that the debug message is displayed. Note that even the first syntax is more readable, the recommended one is the last as all others are now deprecated.


/* global $ */
/**
 * I am using a JavaScript module to isolate the code of each snippet.
 * In fact it's a Vue.js mixin. Take the code called by the mounted()
 * or the snippetXX() function.
 *
 * Open your JavaScript console to check the console.log() calls.
 */
export default {
  methods: {
    snippet66 () {
      $(document).ready(function () {
        console.log('DOM is ready!')
      })

      $(function () {
        console.log('Recommanded syntax for jQuery3')
      })
      // That's it! 😁
    }
  },
  mounted () {
    if (this.isArticle(66)) {
      this.snippet66()
    }
  }
}

 More on Stackoverflow   Read the doc  Random snippet

  Work with me!