Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use `$(document).ready` in TypeScript

Using $(document) in TypeScript gives the error Supplied parameters do not match any signature of call target.

error screen

I'm using TypeScript 3.1, jQuery 3.3.1 and @types/jQuery 3.3.29.

Is $(document) deprecated and I should use something else or is it an error in the type definition file?

EDIT: The entire body of this TypeScript file is basically "Hello World!".

$(document).ready(() => {
    console.log("Hello World!");
});
like image 948
V0ldek Avatar asked Mar 30 '19 14:03

V0ldek


People also ask

What does $( document .ready function () mean?

$( document ).ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

Is document ready deprecated?

There is also $(document). on( "ready", handler ) , deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.

How do I use document ready in JavaScript?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

Which one is equivalent to $( document .ready function?

Answer: Use the DOMContentLoaded Event You can utilize the JavaScript Window's DOMContentLoaded event to construct $(document). ready() equivalent without jQuery.


1 Answers

$(document).ready(handler) has two functionally equivalent variants, first is $().ready(handler), and second is direct $(handler).

In jQuery 3.0 first two were deprecated, leaving only $(handler). The official justification is:

This is because selection has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior.

TypeScript definition files just don't include deprecated syntax, which still works for the sake of backward compatibility. Your script should look like this:

$(() => {
    console.log("Hello World!");
});
like image 169
Arion Avatar answered Oct 12 '22 01:10

Arion