I have a requirement, where i want to fetch certain properties from user profile.For this i have created a file which fetches data from user profile and store in global variable. I was able to add script to modern page and classic page ( Add-PnPJavaScriptLink )

Based on these user profile properties each of my webpart are getting loaded on modern page.

i dont want to call the userprofile js each time for each webpart.

I just want to call it once.Once present in global variable i should be able to access it for all other webparts

But the problem is the custom javascript is getting called after webpart is rendered

any suggestions ?


SharePoint does have a function in the onclick event that looks for any PreSaveItem events. You can create a function called PreSaveAction(); within you client code to have you custom actions run before SharePoint does it's thing after the Save button is clicked. Look at a Save button in a form in Developer Tools, and you will see what I am saying. There is a check at the beginning that says:

onclick="(!PreSaveItem()) return false; blah blah blah"

Try running this function:

PreSaveAction() {
    //do my stuff here

Make sure this function is place above any $(document).ready(function() {});, _spBodyOnLoadFunctionNames.push("myCustom");, or any other page ready type event for it to fire. This should work for you. Hope this helps!

| improve this answer | |

What about creating a global function which would return a promise and also cache the data? Only first call to the function would cause loading the data for the user profile. Subsequent calls would be handled from cache. Using promises would also solve your problem with async calls.

More about promises: https://developers.google.com/web/fundamentals/primers/promises


function getDataGlobal(){
    return new Promise(function(resolve, reject) {
    // Your api call here
    if (/* everything turned out fine */) {
    else {
        reject(Error("It broke"));
//In webpart
 getDataGlobal().then(function(result) {
    console.log(result); /* result is the "yourApiData" from resolve(yourApiData);*/
  }, function(err) {
    console.log(err); // Error: "It broke"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.