Reference files from JS file in page's folder

Hello everyone,

I am a design lecturer and currently building a page to showcase the work of our students. The projects are made with p5.js, which is a JS library similar to processing for Java.

To showcase the projects, I put them all in different folders and included the files. This works, as long as the JS files do not reference any images or similar files.

For Example:

img1 = loadImage('background.png');

There is an imagefile with that name in the page’s folder. However, since the JS file is copied to the media folder, but the image is not (since it’s not called from the html page, but just in the JS file) I get a 404 error. Is there a way to reference files directly from the page folder or automatically move everything without renaming to the media folder? Or just serve the JS file from the page folder?

I am currently running out of ideas on how to implement that, aside from changing hundreds of JS files manually.

For reference, this is how the folder looks:
image

Kind regards,
SG

I would suggest putting them all in the assets folder, that way they will not get copied to the media folder.

I think the problem is actually not that the JS gets copied to the media folder. AFAIK, if you request https://example.com/projects/a-project/background.png Kirby should just redirect you to a /media location and respond with the image (even if you don’t mention it anywhere in your php/html). The base for a relative request is not the location of the js script, it’s the location of the page that is executing it.

So the problem seems to be that the relative path background.png, when called from the page https://example.com/projects/a-project resolves to
https://example.com/projects/background.png instead of
https://example.com/projects/a-project/background.png (the latter should work).

This is because Kirby by default generates URLs without a trailing slash, which look nice, but have a semantically different meaning:

  • https://example.com/projects/a-project means that you are in the projects folder looking at a file called a-project.
  • https://example.com/projects/a-project/ means that you are in the projects/a-project folder looking at the directory index file.

One way to solve this would be to enforce a trailing slash, another way would be to add a <base> tag to your template head:

<base href="<?= $page->url() ?>/"> <!-- notice trailing slash -->

(The <base> tag has to come before the <script> tag that loads the p5 project).