javascript - Ignore script error and carry on loading page -
i have module in nodejs (socketio), , clients load via:
<script type="text/javascript" src="<?php echo $socketserver; ?>socket.io/socket.io.js"></script> <script type="text/javascript"> var socket = io.connect('http://192.168.0.15:8123'); </script> the problem is, if node server offline script break , rest of page stop loading.
my app not depend on node function properly, need carry on loading whether or not node working.
how can done?
if socket.io script optional, can implement lazy loading of script:
function lazyload(url, callback) { var script = document.createelement('script'); script.type = 'text/javascript'; script.src = url; script.onload = script.onreadystatechange = function() { if (script.loaded == false && (!this.readystate || this.readystate == 'complete')) { script.loaded = true; console.log('script loaded'); callback(); } }; script.onerror = function() { console.log('error loading'); } document.body.appendchild(script); } then use way:
lazyload('/socket.io/socket.io.js', function() { try { var socket = io.connect('http://192.168.0.15:8123'); } catch(e) { console.log(e); } }); btw, make sure load , connect socket.io on same server, otherwise face issues cors , many security limitations based on different browsers security policies.
Comments
Post a Comment