How to run a JS function after DOM is complete && server connect is done?

I need to execute a javascript function AFTER both:

How do I do that?

More info:

  1. I have a function that initiates Tiny MCE. It replaces a textarea with the Tiny MCE editor.
function initTinymce(content) {
    // document.onreadystatechange = function () {
    //     if (document.readyState == "complete") {
    console.log('LOADING INIT TINY MCE');
    var globalContent = content;

    tinymce.init({
        selector: 'textarea#tinyEditor',
        setup: function (editor) {
            editor.on('init', function (e) {
                editor.setContent(globalContent);
                editor.save();
            });
            editor.on('change', function () {
                editor.save();
            });
        },
        min_height: 500,
        plugins: [
            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
            'insertdatetime', 'media', 'table', 'help', 'wordcount', 'powerpaste'
        ],
        toolbar: 'undo redo | blocks | ' +
            'bold italic backcolor | alignleft aligncenter ' +
            'alignright alignjustify | bullist numlist outdent indent | ' +
            'removeformat | help',
        content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:16px }'
    });
}
  1. I have a server connect that loads data from the database, this data will populate the textarea that TinyMCE will initiate on.
    For example, it’ll populate: “My text from the database”.

  2. I put a dynamic event ‘on success’ on the server connect, that does a RunJS to trigger the function:

  3. The server connect is finished faster than the DOM changes to the “complete” status (and thus load all the elements and the tinyMCE JS library).

  4. The result: the editor isn’t loaded, it still looks like a regular textarea:

If I run the function initTinymce() in console,it does load in the editor:

So I conclude that the issue is that the server action is loaded (which I need to pre-populate) but the DOM isn’t completed yet.

I need to run the function after BOTH the DOM is complete and the server connect is done. How?

Community Page
Last updated: