Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can code in a JavaScript file get the file's URL?

I need to dynamically load a CSS stylesheet into a page that's on a different domain. How can I get the complete URL of the JS file to use in the href attribute of the stylesheet?

For instance, here is the structure:

http://bla.com/js/script.js

http://bla.com/css/style.css

I want to dynamically load the stylesheet into a page http://boo.net/index.html. The problem is, I don't know the bla.com bit in advance, just the fact that the stylesheet is in ../css/ relative to the JS file.

The script is, of course, included on index.html. jQuery's fine too.

like image 903
montrealist Avatar asked Aug 14 '09 17:08

montrealist


People also ask

How do I get the URL of a JavaScript file?

To retrieve just the URL as a string, the read-only document. URL property can be used. Sun reference: Do not use location as a property of the document object; use the document. URL property instead.

How do I find the URL for an uploaded file?

Answers. string UploadDir=Server. MapPath("~/UploadFolder"); strFileName = Path. Combine( UploadDir,FileUpload1.

How do I find the URL of a string?

Use indexOf() to Check if URL Contains a String When a URL contains a string, you can check for the string's existence using the indexOf method from String. prototype. indexOf() .


1 Answers

Add an ID to the script tag:

<script type="text/javascript" id="myScript" src="http://bla.com/js/script.js"></script>

And in http://bla.com/js/script.js:

var myScript = document.getElementById('myscript');
var myScriptSrc = myScript.getAttribute('src');
alert(myScriptSrc); // included for debugging

You should be able to manipulate the value of myScriptSrc to obtain the path to any other content on bla.com.

I think this sample is what James Black meant in his answer.

Lastly, to everyone suggesting the use of document.location, please keep in mind that if you want read-only access to the current page address, you should be using document.URL or window.location. If you want to set the page address, you should always use window.location.href. Although window.location = 'location'; works, it has always bothered me to see a String being assigned to a Location. I'm not sure why since JavaScript allows all sorts of other implicit type conversions.

  • mozilla reference: document.location was originally a read-only property, although Gecko browsers allow you to assign to it as well. For cross-browser safety, use window.location instead. To retrieve just the URL as a string, the read-only document.URL property can be used.
  • Sun reference: Do not use location as a property of the document object; use the document.URL property instead. The document.location property, which is a synonym for document.URL, is deprecated.
like image 161
Grant Wagner Avatar answered Oct 31 '22 11:10

Grant Wagner