SharePoint: referencing SCRIPT done right
/Our scenario is pretty simple – we have a package that includes some JavaScript files. We had them deployed to /Style Library/ similar to our CSS resources.
We then refer to them in our page layouts and master page via
<script src=”/Style Library/project/myscript.js” />
It works fine on dev.
Problems!
This makes no assumption about the web application or site collections of the destination server. When the site was exported and imported into various different site collection configurations, things start to go silly with 404 script file not found.
Site collection: http://mysharepoint.com/sites/mysite/
The JavaScript then is at: http://mysharepoint.com/sites/mysite/Style Library/project/myscript.js
But the reference is still looking for http://mysharepoint.com/Style Library/project/myscript.js
Oops – 404 error.
Fix!
The solution comes in a two steps:
- Deploy to _layouts/ instead, so the script resource is at
http://mysharepoint.com/sites/mysite/_layouts/project/myscript.js - Use the SharePoint control ScriptLink
<SharePointWebControls:ScriptLink Name=”/project/myscript.js” Localizable=”false” runat=”Server” /> - The localizable = false is important – otherwise SharePoint will look for
http://mysharepoint.com/sites/mysite/_layouts/~language/project/myscript.js