I have a javascript module which creates a div with a picture of a close button (“X”).
This div and javascript are placed in many places on my site.
Relative path solution: When a page includes the javascript, and the javascript uses a relative path for the image. The relative path is relative to the HTML-page. If HTML pages in different paths use this javascript I will need 2 different images.
Absolute path solution: I do not know what server my team-member is using for development (I know for sure that he is not developing on my server). This means that absolute paths will not work.
Is there a simple way of overcoming this problem? Like making the script somehow aware of its path?
Mutable paths (test/staging/production domains) is always a problem in javascript, the best option is to include the root path of your application/website in the HTML. The obvious place to do this is in your template layer. For example:
And grab it with javascript for usage in your scripts.
Note, you can only do this when the DOM is ready (or when document.body is available, differs cross browser) 😉
An alternative and in my view less pretty option is to simply render javascript.
At least with the ‘data-root’ technique, you can store the value wherever you like and avoid a global definition.
So in your code where you reference an image, you can do the following:
Or create a nice helper method:
In the helper method, you can also write some code to ensure proper uses of / and whatnot.