In this article, I’ll share one little finding, which I recently found. This is related to the current user profile image, which we need to show on our SharePoint Online site in our custom master page. Generally in JSOM, whenever we call/ load something, we need call backs. Thus, we need to depend on either respective success or failure method. Here, I’ll share how we can get current user or any user profile image without Callback.
Background
In our one of SharePoint Online sites, we need to show current logged in user profile image. We have our custom master page. Thus, we need to basically get the current user property – “Picture URL” and render. Since there is not another option we can find, we have implemented it, using JSOM. Thus, code is really simple, as shown below.
Note
Here, I only shared sample code and not the complete one.
We have written one method fetchUserDetails, which loads the user details, as shown below.
- SP.SOD.executeOrDelayUntilScriptLoaded(fetchUserDetails, 'SP.UserProfiles.js');
- var userProfileProperties;
-
- function fetchUserDetails() {
-
- var clientContext = new SP.ClientContext.get_current();
-
- var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
-
- userProfileProperties = peopleManager.getMyProperties();
-
- clientContext.load(userProfileProperties);
-
- clientContext.executeQueryAsync(onfetchUserDetailsSuccess, onfail);
- }
- Success method as below
-
- function onfetchUserDetailsSuccess() {
-
- var pictureUrl = userProfileProperties.get_pictureUrl();
-
- alert(pictureUrl);
- }
Disadvantage of above approach
There is nothing wrong in the approach given above but then we need to wait for the Callback and then we get the profile image for the current user. It’s not like that we will directly get the current user profile image, so it’s also a bit like lazy loading.
New approach
While Googling for some issue, I found that there is Delve Service, which directly returns any user profile image without call back. Service name is DelveApi.ashx and way to call is given below.
-
- var currentSiteURL = _spPageContextInfo.siteAbsoluteUrl;
-
- var delveServiceURL = currentSiteURL + "/_vti_bin/DelveApi.ashx/people/profileimage?userId=" + _spPageContextInfo.userLoginName + "&size=L";
We can also mention the size (L, M and S). Actually, this Service downloads the respective image, as per the specified size. Hence, we can either use “div” tag or “img” tag and set the “src” property of them. No dependency on Callback or there is no need to handle the failed method.
One more benefit of using this approach is, if we know the login name of the user, we can easily download the profile image by specifying respective login name to the userId parameter. Currently, we are passing current logged in user’s login name. This is useful where in some scenarios; we need to show the users' listing.
I hope, you will find this little finding useful.
Thanks.