I have a webpart and I want to reference a js file in the content link. But I don't want to hardcode the full absolute path. I want to use the relative url. The js is located in the style library folder.

The problem is I can't find out how to use the relative path. I tried

../../Style Library/username.js

But then this breaks if I use this same link in a subsite. Because the number of .. is changed. I want a link that will work from anywhere. I tried ~sitecollection/Style Library/username.js

but SharePoint doesn't evaluate the ~ variable into the path. Does anyone know how to do this? Thanks.

  • In situations like that I usually just edit out the hostname from the absolute URL. So instead of http:/ /server/sites/sitename/Style Library/etc.js I just use /sites/sitename/Style Library/etc.js. – Dylan Cristy Jul 13 '15 at 20:39
  • But then your assuming /sites/ is there in any environment, but thats only specific to your environment. I want something that will work in any environment. – omega Jul 13 '15 at 20:41
  • Yeah, it's a shame that the URL tokens don't work for that. – Dylan Cristy Jul 13 '15 at 20:50

Using JS define the URL as _spPageContextInfo.siteAbsoluteUrl + "/Style Library/username.js"

Read more about the _spPageContextInfo:


If the JS should be referenced on the web part's properties and the ~sitecollection doesn't seem to do the work, replace the ~ mark with ~.

| improve this answer | |
  • It should rather be _spPageContextInfo.siteAbsoluteUrl as Style Library will most often be present in root site collection. So even if you are in a sub site the Url generated through _spPageContextInfo.siteAbsoluteUrl will be same. – Nadeem Yousuf-AIS Jul 14 '15 at 9:15
  • But how do I use this in the web part content link? – omega Jul 14 '15 at 12:01
  • @omega See my updated answer. – moe Jul 14 '15 at 12:54

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.