socket.io, io is not defined (JS Error)

前端 未结 9 769
你的背包
你的背包 2021-01-03 20:33

I have just started with socket.io, its giving JS Error on client page

io is not defined

How to fix this ?

9条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 21:10

    I have a socket app where my server (not a CDN) is serving up the socket.io.js script. So, while Emmerman is right in saying that you need to include the script tag in your client HTML code, the asset won't be loaded if your back-end is down. One option is for you to write a client-side JS script that checks for io before you try and use socket.io. If it's not present (undefined/null) then you can either conditionally show something else like, "server down" or in my case, I'm going to set a timer that keeps checking periodically until the server is restored.

    [UPDATE 2] Ended up having to include the script tag, check for existence of io object and doing a window.location.reload() after 10 seconds (using setTimeout) (which eventually will hopefully find that the script loaded and io exists, after which I can connect to the socket server.)

    [UPDATE] I'm loading the script with an ajax call rather than using an html script tag. Then with the timer I'm checking periodically if the script will load – eventually it will when the server is restored/rebooted. jQuery ref to load JS scripts dynamically: http://api.jquery.com/jQuery.getScript/

提交回复
热议问题