1

Actually I was trying to get the concept of the module pattern. Here I have simple code which I used to type directly on the page. It was fine until I tried to separate the actual code from the HTML file and kept only a single line of code on the main HTML file:

<body>
    <script type='text/javascript' src='module.js'>
        // module.JS file was here ....
        document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
    </script>
</body>

File module.JS

var module = (function() {
    return {
        show:function(keyCode){
            document.body.innerHTML+=(String.fromCharCode(keyCode));
        }
    };
})();

2 Answers 2

3

You'll need to have two <script> elements for this.

Use one to "import" your external module and another for the script you want to embed directly on the page:

<script type='text/javascript' src='module.js'></script>

<script type='text/javascript'>
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>

For more information, you can check out this MDN documentation page. Here is an excerpt talking about the src attribute (emphasis added):

This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document. Script elements with an src attribute specified should not have a script embedded within its tags.

1
1

A script block referring to an external JavaScript source should be separate and any script inside of it does not get executed. So you need two separate script blocks one for the external JavaScript file and the other for your script.

<script src='module.js'></script>

<script>
    document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>
1
  • It does not have to be empty, can be used for data, but the script code will not be executed.
    – Cheery
    Oct 19, 2014 at 8:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.