简体   繁体   中英

Javascript getting called before the SPFX Webpart loaded on the sharepoint page

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.

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.

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) 

PS 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM