Tuesday, June 16, 2009

SharePoint Site Relative CEWP Included Script

This post is about injecting site relative JavaScript include files in SharePoint using CEWP. It is not about injecting JavaScript files using the server-side ASP.NET script manager or any other server-side mechanism.

We all know that the src attribute of the <script> element is either page relative or server relative; or God forbid, absolute. You cannot use the tilde (~) to make the URL site relative, but you can achieve this using the SharePoint page L_Menu_BaseUrl variable and inject the include file into the page dynamically:

<script type="text/javascript">
' src="' + L_Menu_BaseUrl +'/ScriptLibrary/SiteSpecificScript.js"',

' type="text/javascript"><\/script>');

This actually makes the include file URL server relative, but without hardcoding the site path into the URL - making it equivalent to being site relative.


Christophe said...

This should work:


Christophe said...

Or maybe I misunderstood, and you were talking about linking to a script within the site. In this case I wouldn't use jQuery as an example, as this is typically a script that you want to put in a central location and share across sites...

Kjell-Sverre Jerijærvi said...

Yes, you're right, I'll change the example to a site specific script.

This posting is just a sidebar to another post, where I recommend storing the jQuery library in a central place such as the top site of the root site-collection.

Anonymous said...

Christophe's solution is probably only for toy sharepoint farms with a single site collection.

The post is about generating a path to a library in the current site collection (on a real, production farm with multiple site collections), without hardcoding in the site collection url.

Anonymous said...

will the same code work for 2013 list also

Kjell-Sverre Jerijærvi said...

Only if the js variable is still defined, alas most front end code has changed