Search code examples
javascripthtmlassets

Is it possible to load remote javascript that uses local assets (with respect to itself)?


I want a webpage to execute a remotely hosted js script. The script makes use of image-assets within the script's own directory. Is this possible to do using only relative filepaths within the script?

When run remotely, the relative filepath is interpreted as relative-to-the-webpage-file, not relative to the remote script itself.

I'd like to handle this without modifying the script to use absolute paths, because it's intended to be transportable. The webpage is just a showcase for the project. Is this possible to do in HTML?

Specifically, I have a javascript file being served by github pages eg:

https://user.github.io/repo/script.js

which uses some image assets, located in that repo, eg:

https://user.github.io/repo/assets/image.png

The script uses local paths to load its assets, eg:

imgBird = loadImage('assets/bird.png');

This doesn't work when the script is loaded remotely, because the script looks within the directory of the webpage for assets/bird.png, not the remote resource.

The HTML source currently uses the following to attempt to run the script:

<script src="https://user.github.io/repo/script.js">

There exists a similar problem, but the answer is script-based. I want to avoid modifying how the script works because it's intended to be introductory-level scripting and easy to understand.


Solution

  • No. Paths are relative to the page containing the script tag, not the script itself. For the script to function correctly it will need to know the url for /assets.