Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics Hello, JavaScript! JavaScript Challenge Solution

JavaScript Challenge Solution alternative by writing JavaScript code directly in the HTML

When completing the JavaScript Challenge, I opted to write the code directly into the HTML with the <script></script> function, rather than edit the provided .js file. I'm not sure why that was the first solution to come to me, and while my solution appears to work as intended, I'd like to know if I wrote this code correctly, how it could be better, or if there are any hidden implications to doing this vs. writing in the .js file. Any and all feedback is appreciated! Here's what I ended up with:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>JavaScript Basics – Challenge</title>
    <link href="css/style.css" rel="stylesheet">
    <script>
      alert("Warning! This message will self-destruct in");
      alert("3...");
      alert("2...");
      alert("1...");
    </script>
  </head>
  <body>
    <main>
      <h1>Hello, JavaScript!</h1>
    </main>
    <script src="js/script.js"></script>
    <script>
    console.log("Message destroyed!");
    </script>
  </body>
</html>

Thanks T. Gontarek ! Appreciate the feedback and additional insight, totally makes sense.

1 Answer

Your going to learn more about why this is considered bad practice. But often you will find this method for learning the basics of JavaScript. One, the browser loads things in the order that it is seen. Meaning top down. Best practice is to do all of your scripts on its own file. Then link the file at the bottom of the html file, just above the closing body tag </body> . This lets the HTML and CSS load before the JS loads helping with site load times. There is another method that you can also use. This will allow JS to be linked to the top of the page, in the head where everything else is.

Congrats on the successful code! It's really neat isn't it!

https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event