How to subscribe to document.ready event from multiple TypeScript files

What I needed :

I needed to subscribe from multiple TypeScript files to ready event of document, the usual event where you hook to do some initializations with jQuery, when you need it. There are more ways, to do this.

  • You can handle the ready event on the “host” page and do what you need to do there,
  • You can, if you know you are the only one just inject your anonymous function to say window.onload but there is a problem, that the last pointer wins and you can have only one function there, just try this in you page :
    <script>
             window.onload = function() {
                 console.log('1');
             };
             window.onload = function () {
                 console.log('2');
             };
    </script>
    

    There will be only one line in console, with 2.

  • Somehow subscribe to the ready event and call all pointers no matter who subscribed and will subscribe in the host page.

First of all there are some things to clarify :

How to do it :

Since TypeScript is in fact JavaScript (its superset of JavaScript), you can use it without TS (btw I don’t use any feature from TS, maybe we could change

$(document).ready(function () {
         console.log('ts 2');
});

to :

$(document).ready(() => {
         console.log('ts 1');
});

But whatever 🙂

The key is to :

  • use jQuery in your project,
  • use everywhere $(document).ready since it will subscribe your code to the jQuery ready event and essentially chain them it the order as browser parsed the .js files,
  • include jquery.d.ts definition for TypeScript to be happy (part from DefinitelyTyped project)

The snippet of subscription code can be placed after module and class definitions in each .ts file so you can do what you need. TypeScript will just copy this JS to the resulting .js file.

In case of any questions, something interesting, another take on the same problem > please share in comments, thank you.

Download link : sample app

2 thoughts on “How to subscribe to document.ready event from multiple TypeScript files

  1. there are two more shortcuts for cleaner code:

    1. use overload of $ function with function parameter
    2. use arrow function in typescript

    example:
    $(() => {

    });

Leave a Reply

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