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));
        }
    };
})();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AL-zami
  • 8,902
  • 15
  • 71
  • 130

2 Answers2

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.

Lix
  • 47,311
  • 12
  • 103
  • 131
  • 3
    And more information as to *why* this is the case: http://stackoverflow.com/questions/6528325/what-does-a-script-tag-with-src-and-content-mean – CodingIntrigue Oct 19 '14 at 08:17
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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36
  • It does not have to be empty, can be used for data, but the script code will not be executed. – Cheery Oct 19 '14 at 08:17