0

i'd like to isolate the javascript code from the html code in two diferent files, originally I had this code:

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
    </head>
    <body>
        <p id="body">HTML Text</p>
    </body>
</html>
<script>
        $(document).ready(function () {
            $("#body").text("JS Text");
         });
</script>

and the output of the <-p-> was the expected "JS Text".

Then I tried to isolate the js script to another file (script.js):

window.onload = function(){
    var text = document.getElementById('body');
    text.innerHTML ='JS Text';
}

I've also make the reference at the html file:

<script type="text/javascript"src="scripts.js"></script>

but then the output text is no longer the expected (JS Text) but (HTML text)

what else do I need to make the js script work again?

3
  • Do you get any errors in your console? Commented May 23, 2019 at 22:18
  • You want to be sure that the document is loaded, not the window. Commented May 23, 2019 at 22:21
  • 1
    Also, where are you loading jQuery? Commented May 23, 2019 at 22:23

1 Answer 1

1

First, it is invalid to place anything after the closing HTML tag, so while your first bit of code worked, it was invalid.

If you remove the JavaScript and place it in its own file, it will continue to work as long as you reference the file properly (use a relative reference and test the file on a web server) and place the script element just prior to the closing body tag so that when the script is processed and attempts to find the right DOM element, the DOM will have been loaded at that time.

FYI:

  • If you have JQuery in the referenced script file, then your script that references JQuery will need to occur in the HTML prior to the script that uses it.
  • The type attribute in the script tag has not been needed in several years.
  • It's not a good idea to name anything body so that you won't cause confusion with the body element.
  • Don't use .innerHTML when the string you are working with doesn't contain any HTML. .innerHTML has security and performance implications. Use .textContent instead.

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
    </head>
    <body>
        <p id="body">HTML Text</p>
        <script src="relativePathToFile.js"></script>
    </body>
</html>

Sign up to request clarification or add additional context in comments.

1 Comment

@D_N Everything one needs to know about how to do this correctly is addressed in the answer. You don't need to write a novel to answer a simple question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.