title: Javascript Websocket closed unexpectedly when script is loaded externally
body: <p>While building a chat application in Django, I used embedded javascript and it worked. But, if I write the same code in external javascript then the WebSocket gets closed. I have checked all the links and static file path. The script is loaded completely but the WebSockets gets closed after they open.</p>
  
  <p><a href="https://channels.readthedocs.io/en/latest/tutorial/part_2.html#add-the-room-view" rel="nofollow noreferrer">Here's the tutorial from Official Django Channels website</a>, and that javascript is working in embedded form only not in an external script.</p>
  
  <p>And, <a href="https://github.com/m0hitnegi/chat-con/blob/master/interface/templates/interface/index.html" rel="nofollow noreferrer">here's my Github repo</a> where I've implemented Websockets.
  How can I write JS code in external script instead of embedded? I've Googled but found no help and even <a href="https://stackoverflow.com/questions/34719970/websocket-connection-is-not-working-when-script-is-loaded-from-external-source">this</a> question hasn't been answered yet.</p>
  
  <p>Here's the code I'm talking about and the websockets won't work if defined externally:</p>
  
  <pre><code>&lt;!-- chat/templates/chat/room.html --&gt;
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;meta charset="utf-8"/&gt;
      &lt;title&gt;Chat Room&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;textarea id="chat-log" cols="100" rows="20"&gt;&lt;/textarea&gt;&lt;br/&gt;
      &lt;input id="chat-message-input" type="text" size="100"/&gt;&lt;br/&gt;
      &lt;input id="chat-message-submit" type="button" value="Send"/&gt;
  &lt;/body&gt;
  &lt;script&gt;
      var roomName = {{ room_name_json }};
  
      var chatSocket = new WebSocket(
          'ws://' + window.location.host +
          '/ws/chat/' + roomName + '/');
  
      chatSocket.onmessage = function(e) {
          var data = JSON.parse(e.data);
          var message = data['message'];
          document.querySelector('#chat-log').value += (message + '\n');
      };
  
      chatSocket.onclose = function(e) {
          console.error('Chat socket closed unexpectedly');
      };
  
      document.querySelector('#chat-message-input').focus();
      document.querySelector('#chat-message-input').onkeyup = function(e) {
          if (e.keyCode === 13) {  // enter, return
              document.querySelector('#chat-message-submit').click();
          }
      };
  
      document.querySelector('#chat-message-submit').onclick = function(e) {
          var messageInputDom = document.querySelector('#chat-message-input');
          var message = messageInputDom.value;
          chatSocket.send(JSON.stringify({
              'message': message
          }));
  
          messageInputDom.value = '';
      };
  &lt;/script&gt;
  &lt;/html&gt;
  </code></pre>