Office.onReady

Office.onReady() is an asynchronous method that returns a Promise object while it checks to see if the Office.js library is fully loaded.
When, and only when, the library is loaded, it resolves the Promise as an object.
That object specifies the Office host application with an Office.HostType enum value and the platform with an Office.PlatformType enum value.
If the library is already loaded when Office.onReady() is called, then the Promise resolves immediately.
One way to call Office.onReady() is to pass it a callback method


Office.onReady(function(info) { 
    if (info.host === Office.HostType.Excel) {
        // Do Excel-specific initialization (for example, make add-in task pane's
        // appearance compatible with Excel "green").
    }
    if (info.platform === Office.PlatformType.PC) {
        // Make minor layout changes in the task pane.
    }
    console.log(`Office.js is now ready in ${info.host} on ${info.platform}`);
});

Instead of passing a callback you could chain a then() method to the Office.onReady()

Office.onReady() 
    .then(function() {
        if (!Office.context.requirements.isSetSupported('ExcelApi', '1.7')) {
            console.log("Sorry, this add-in only works with newer versions of Excel.");
        }
    });

The equivalent written in TypeScript would be

(async () => { 
    await Office.onReady();
    if (!Office.context.requirements.isSetSupported('ExcelApi', '1.7')) {
        console.log("Sorry, this add-in only works with newer versions of Excel.");
    }
})();

If you are using additional JavaScript frameworks that include their own initialization handler or tests, these should be usually be placed within the response to Office.onReady().
For example, JQuery's $(document).ready() function would be referenced as follows:

Office.onReady(function() { 
    // Office is ready
    $(document).ready(function () {
        // The document is ready
    });
});


Exceptions

There are exceptions to this practice.
For example, suppose you want to open your add-in in a browser (instead of sideload it in an Office host) in order to debug your UI with browser tools. Since Office.js won't load in the browser, onReady won't run and the $(document).ready won't run if it's called inside the Office onReady.
Another exception: you want a progress indicator to appear in the task pane while the add-in is loading. In this scenario, your code should call the jQuery ready and use it's callback to render the progress indicator. Then the Office onReady's callback can replace the progress indicator with the final UI.



© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext