Defining JavaScript and other assets using ScriptResource.axd and WebResource.axd

A resource is a file embedded in an assembly. This file can either be an Image, a javascript file or any other emendable type of resource in an assembly.

This is a 2 step process: First, we make a DLL which contains those resource files, then we use them on our HTML page.

1) Make a new Class Library project, add a reference to System.Web and some resources. It should look like this (I added a .js and a .jpg file):


2) Open Class1.cs and add the following code:

using System;
using System.Web;
using System.Web.UI;
using System.Security.Permissions;

[assembly: WebResource("ClassLibrary1.Image1.jpg", "image/jpeg")]
[assembly: WebResource("ClassLibrary1.JavaScript1.js", "application/javascript")]
namespace ClassLibrary1
		Level = AspNetHostingPermissionLevel.Minimal)]
	public class Class1 { }

The AspNetHostingPermission attribute controls access permissions in ASP.NET hosted environments.

3) Change the Build Action of both resource files to Embedded Resource:


4) Build the project.

5) Open your web site project, right-click and add a reference to this DLL we just built.


6) There are a few ways you can reference those resources on your HTML markup. You can wither do it on code-behind, which I prefer:

protected void Page_Load(Object sender, EventArgs e)
	string jsUrl = Page.ClientScript.GetWebResourceUrl(typeof(ClassLibrary1.Class1),

	ScriptManager.RegisterStartupScript(this, this.GetType(), "JavaScript1",
		"<script src='" + jsUrl + "' type='text/javascript'></script>", false);

	img.ImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(ClassLibrary1.Class1),
		"ClassLibrary1.Image1.jpg" );

You can also paste the resource URL (given by GetWebResourceUrl()) directly onto your HTML markup without using ScriptManager or code-behind.

Different versions of ASP.NET will require extra work, this example was done in ASP.NET 4.

In case it doesn’t work, make sure you have the HttpHandler entry on your web.config as described here


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s