Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference a javascript file?

I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.

However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.

Does anybody have any ideas for resolving this?

like image 900
Guy Avatar asked Sep 04 '08 05:09

Guy


People also ask

Where do I put JavaScript script files?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body.

How do I connect JavaScript and HTML?

Adding JavaScript into an HTML Document You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.


2 Answers

If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work.

You could also do this in your Page_Load (In your masterpage):

Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js"))
like image 65
Espo Avatar answered Oct 27 '22 14:10

Espo


Try something like this in the Master Page:

<script type="text/javascript" src="<%= Response.ApplyAppPathModifier("~/javascript/globaljs.aspx") %>"></script>

For whatever reason, I've found the browsers to be quite finicky about the final tag, so just ending the tag with /> doesn't seem to work.

like image 26
Jared Avatar answered Oct 27 '22 12:10

Jared