Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Import from Relative URL (Browser)

Is there a way to import a Javascript file from a URL (relative) in the browser from Javascript code?

I know you can import a Javascript file from HTML but I don’t want to do that.

I would expect something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { functionName } from "/static/javascript/fileName";

functionName();

>Solution :

Yes, relative URLs are absolutely fine. A couple of things to note:

  • Like all other relative URLs in the browser environment, they’re resolved client-side.
  • Your import is syntactically correct, but you probably meant to have .js on there, because browsers do not add file extensions for you.

If your import were in a file at https://example.com/something/somefile.js, your import would be telling the browser to import from https://example.com/static/javascript/fileName.

Guessing a bit from the name of your path, you probably wanted:

import { functionName } from "./fileName.js";

That tells the browser to import from fileName.js on the same path as the JavaScript file the import occurs in. So if the import were in https://example.com/something/somefile.js, the browser would look for https://example.com/something/fileName.js.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading