Problem running external script

Asked

Viewed 70 times

0

Good afternoon

I am learning the basis of building a web page and at this stage the structure of it is

<html>
<head>
<script src="script/download.js"></script> 
<title>
A Simple HTML Document
</title>
</head>
<body>
<p>This is a very simple HTML document</p>
<p>It only has two paragraphs</p>
</body>
</html>

where I have a javascript file in the script folder and the page is opening it locally

the javascript file is

var link = document.createElement('a');
link.href = 'http://server/file.exe';
link.download = '';
document.body.appendChild(link);
link.click();

it happens that when I try to open the web page no download is done What could be the mistake here?

Thank you

  • You are running the code before there is one body. Probably on the console is showing error: Cannot read property 'appendChild' of null

  • with effect on the console says Typeerror: Document.body is nulldownload.js:4:1 <anonymous> file:///C:/Users//site/script/download.js:4

  • I apologize for this basic question, but what is the reason for the error?

  • I explained in response. Abs!

1 answer

0


How your script is in <head>, it will run before the browser builds the body, and you’re trying to access the body that does not yet exist in the DOM, resulting in error:

Cannot read Property 'appendchild' of null

Javascript always returns error when you try to access a property (actually the appendChild() is a method) of an object that does not exist (null).

What you can do is run the code within an event that awaits the DOM to be loaded:

document.addEventListener("DOMContentLoaded", function(){
   var link = document.createElement('a');
   link.href = 'http://server/file.exe';
   link.download = '';
   document.body.appendChild(link);
   link.click();
});

Or load the script at the end of body:

<html>
   <head>
      <title>
         A Simple HTML Document
      </title>
   </head>
   <body>
      <p>This is a very simple HTML document</p>
      <p>It only has two paragraphs</p>
      <script src="script/download.js"></script> <!-- CARREGA AQUI -->
   </body>
</html>
  • Thank you very much. Both solutions worked :)

  • Learn how to thank on [tour]. Abs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.