Home > database >  Importing module of scripts and onload DOM
Importing module of scripts and onload DOM

Time:09-01

What is the difference between doing this:

import $ from "jquery";

import { getCurrentYear } from "../utils/global/functions";

$("#year").text(getCurrentYear());

and this:

import $ from "jquery";

import { getCurrentYear } from "../utils/global/functions";

function setCopyrightYear() {
  $("#year").text(getCurrentYear());
}

$(setCopyrightYear);

If I import both modules in the head section of my HTML page like this:

<head>
    <script type="module" src="../js/scripts/home.js"></script>
</head>

CodePudding user response:

Passing a function to $ is equivalent to the ready method which:

run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate

However, a <script> with type=module is a module so:

There is no need to use the defer attribute (see <script> attributes) when loading a module script; modules are deferred automatically.

… which has approximately the same effect, making the use of $(callback) pointless.

  • Related