1

I have created Sharepoint Page with custom masterpage where I have deployed my SPFx Webpart which needs some javascript files.

Sometimes the Webpart works fine but sometimes not due to my javascript called before SPFx gets loaded on DOM.(I also tried to put javascript in custom masterpage still facing same issue)

I googled out for the same and Reference

I did the modification in the javascript function with same by calling function on load event instead of ready function. After modification it works fine in chrome browser but it's not working properly in IE and Firefox.

Is there any other way to get the proper outcome.

Mr. Roshan
  • 1,777
  • 13
  • 33

2 Answers2

2

Basically, in case, it is just a simple wait, one thing you can do is to wait for DOMContentLoaded. This is a cross-browser event listener that works in firefox and even goes back all the way to ie9.

// Option 1
    window.addEventListener("DOMContentLoaded", function () {
        console.log('ready')
    }, false);

In case your SPFx code creates the element only later on, you can wait for one of the elements it creates, check for if it exists and only then invokes your function like so:

// Option 2
// Wait for the DOM element to be in the DOM
const inDom = (selector, timeout = 1000, callback) => {
    const interval = setInterval(() => {
        const elem = document.querySelector(selector);
        if (elem) {
            clearInterval(interval);
            // Do stuff
            callback()
        } else {
            console.log('Not in dom')
        }
    }, timeout);
};

// Wait 3 seconds and add the element to the DOM
setTimeout(() => {
    document.body.innerHTML = document.body.innerHTML + "<div id='test-div'>TEST</div>";
}, 3000);

const myAwesomeFunction = () => console.log('Element in dom');

inDom('#test-div', 1000, myAwesomeFunction)

P.S. You probably would like to add a fallback in case the element is nowhere to be found after some period, otherwise the interval will run forever.

Shahar
  • 2,101
  • 18
  • 23
  • Thanks.! There is one problem if we use setTimeout function then it will work fine but in the low bandwidth it is not good approach and also decreases the performance – Mr. Roshan Aug 19 '19 at 12:01
1

You can control the loading behaviour of external scripts with the attributes async and defer.

From the MDN web docs:

defer: This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

async: This is a Boolean attribute indicating that the browser should, if possible, load the script asynchronously.

Community
  • 1
  • 1
SparkFountain
  • 2,110
  • 15
  • 35