简体   繁体   中英

How to use relative paths to scripts in HTML

I am trying to refer to my JS/CSS with a relative path, like ./myScript.js , such that, if I host the site on https://myHost.com/myPath , it should look for the script in https://myHost.com/myPath/myScript.js , but if I host it on http://localhost/ , it should look in http://localhost/myScript.js . It is always looking in the root though, as if I had made an absolute path.

Is it not possible to make relative paths? I would prefer if I did not need to change the actual HTML file between environments.

Example

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <link rel="icon" href="./favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Web site created using create-react-app" />
    <link rel="apple-touch-icon" href="./logo192.png" />
    <link rel="manifest" href="./manifest.json" />
    <title>React App</title>
    <link href="./static/css/main.6dea0f05.chunk.css" rel="stylesheet">
</head>

<body><noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script>/* a bunch of auto generated react code */</script>
    <script src="./static/js/2.1ca84f3b.chunk.js"></script>
    <script src="./static/js/main.487a42e6.chunk.js"></script>
</body>

</html>

This is one of those times that I spend 2 hours fiddling with it, to no avail, post a question, and then find the answer directly after..

The issue is that I automatically return index.html if users do not specify it, making chrome think that the current "folder" is the root when accessing https://myHost.com/myPath . If I go to https://myHost.com/myPath/index.html it works.

So, I need to do a proper redirect to index.html , instead of just returning it. Or to anything under myPath , like https://myHost.com/myPath/home .

Try to use this:

<base href="https://www.w3schools.com/">

I hopes, that it helps for you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM