Help me understand the html function from javascript
-
We need to call a function.
init()
♪onClick
buttons. In turn, the function is triggered when the page is downloaded! How do we create a function from the file? And why is the function performed arbitrarily when the page is downloaded?ws.js
var wsUri = "wss://echo.websocket.org/"; var output; function init() { output = document.getElementById("output"); alert('gjxtve'); testWebSocket(); }
function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}function onOpen(evt)
{
writeToScreen("CONNECTED");
alert('connected');
doSend("WebSocket rocks");
}function onClose(evt)
{
writeToScreen("DISCONNECTED");
alert('DISCONNECTED');
}function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
alert(evt.data);
websocket.close();
}function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
alert(evt.data);
}function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}window.addEventListener("load", init, false);
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<head>
<script type="text/javascript" src="ws.js"> </script>
</head><body>
<h2>WebSocket Test</h2>
<input text="connect" type="button" onclick="init()">
<div id="output"></div>
</body>
</html>
-
And why is the function performed arbitrarily when the page is downloaded?
window.addEventListener("load", init, false);
This line adds to the processor load♪ When this event occurs, the function arises in♪
If you remove this line, the function will only be triggered by the button.