How to reference documents in my website to be independent of the website location and usage location

I'm relatively new to client side development. I'm creating an angularJS directive which references a static html, in [root]/Static/template.html.

I guess the problem is not unique to angularJS.

Now I need this address to be root relative, so that it can be loaded regardless of where I use the directive. The problem is that I don't know where my site will be uploaded, so it might be put in www.mysite.com/ or might be www.mysite.com/system/

I also can't use relative path, as it will be sensitive to where I use the directive, so for instance if I use Static/template.html, it will be found by documents in the website root, but not in the inner folders.

What is the correct way to reference documents to be robust?

Answers


If your static folder is relative the place where your application is deployed, e.g.:

www.example.com/index.html www.example.com/Static

www.example.com/root/index.html www.example.com/root/Static

www.example.com/root/foobar-app/index.html www.example.com/root/foobar-app/Static

Then you need to extract the base url and store it somewhere. window.location API could be used to do that.

E.g.:

<!-- index.html -->
<!-- should probably be placed into external script file -->
<script>
    function extractPath(url) {
        return url.match(/.*\//) // find all chars until the slash
    }

    var baseurl = window.location.origin + extractPath(window.location.pathname);
    window.baseurl = baseurl; // store in global scope
</script>

This snippet shows the general idea. Now elsewhere in your code you can read the base url path to access static resources. E.g.:

var image_url = window.baseurl + "Static" + image_path;

In AngularJS you would normally store that variable in the main app controller. If you only have one factory to access static resources, you could consider storing the baseurl there.


URL that starts with / is the URL from the root.

So if you set /Static/template.html, you can access template.html from both paths(www.mysite.com/ and www.mysite.com/system/).


Need Your Help

Ninject dynamically constructor parameters

c# dependency-injection ninject

In a WebApi project I have a class SyncProductsHelper. This class has two properties, a constructor and some methods:

JasperReport Components

java reporting jasper-reports

New to JasperReports and attempting to either: (a) manually write a JRXML or (b) manually program a JasperDesign myself (not using a template). My understanding is that both the XML and the Java ob...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.