简体   繁体   中英

External Javascript file not working in HTML

This is extremely basic but I'm unsure why this has stopped working. I have the following html file

<html>
<!doctype html>
<head>
  
   <script> document.write("this is working")</script>
   <p>this is working</p>

</head>
<body>
    <script src="test.js"></script>
</body>
</html>

and the following javascript file that is in the same folder as the html file

document.write("Hello World!");

The scripts and html within the html document work fine. However, the external javascript file does not get executed. I have tried with a variety of scripts in the js file and minor modifications to the html file. On a windows 10 computer.

Note this is not a repeated question, the other questions similar to this one were slightly different.

EDIT: Error in browser console states "not allowed to load local source" This may be a chrome security issue. EDIT: Same case in all browsers so doesn't seem purely related to chrome. Attempted all the fixes I could find but did not work.

EDIT: I tried using both node and python for the server.

Looks like you're loading the HTML file through file protocol (ie double-clicking the file and opening it in a browser). In that case, browser may deny to load any external resources ( test.js script in your case) due to security. Load the HTML through HTTP protocol. It can be achieved numerous ways.

  • If you have PHP installed, simply running php -S localhost:80 within the project directory will spin up a local server, which you can browse by visiting http://localhost . It will then serve the index.html page by default.
  • If you have Node.js installed (thus npm , too), install http-server globally ( npm i http-server -g ). And afterthat, run http-server within the project directory. By default, it will spin up a local server on port 8080 , so you'll be able to visit http://localhost:8080 and index.html will be served.

I tried the later one, and your above code worked perfectly fine.

This is not a solution, but it is a work around if anyone has the same issue and a better answer is not produced.

Get the chrome extension "web server" and open that rather than running it through node, python, etc.

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