javascript - Script injected with innerHTML doesn't trigger onload and onerror -
i trying bind onload
, onerror
events of script
tag. works fine when loading src. given following function:
function injectjs(src, inline) { var script = document.createelement("script"); if (inline) { script.innerhtml = src; } else { script.src = src; } script.onload = function() {console.log("success!");}; script.onerror = function() {console.log("error!");}; document.body.appendchild(script); }
i can know whether script has loaded:
> injectjs("https://code.jquery.com/jquery-3.1.1.min.js"); success! > injectjs("https://raw.githubusercontent.com/eligrey/filesaver.js/master/filesaver.js"); error!
but when injecting inline js, innerhtml, script doesn't fire events:
> injectjs("console.log(\"yes!\");", true); yes! > injectjs("console.log(\"loaded error...\"); error;", true); loaded error...
success!
hasn't been logged in these cases. however, prepend code can call function, example, once script loaded.
the problem comes when there error prevents script loading in first place, example syntax error:
> injectjs("console.log(\"success! or not..\"); syntax error;", true);
nothing logged (except error, of course). how can detect whether injected script has loaded or errored out before loading?
edit:
oriol's answer has pointed me in right direction. reference, here final function works wanted , passes 5 test cases:
function injectjs(src, inline, on_success, on_error) { var script = document.createelement("script"); script.onload = on_success; script.onerror = on_error; if (inline) { script.innerhtml = "window.script_loaded = true; " + src; } else { script.src = src; } document.body.appendchild(script); if (inline) { var loaded = window["script_loaded"]; window.script_loaded = false; if (loaded) { on_success(); } else { on_error(); } } }
inline scripts loaded synchronously. don't need events @ all.
just use
function injectjs(src, inline) { var script = document.createelement("script"); script.onload = function() {console.log("success!");}; script.onerror = function() {console.log("error!");}; if (inline) { script.innerhtml = src; script.onload(); } else { script.src = src; } document.body.appendchild(script); } injectjs("console.log(\"yes!\");", true);
you won't able detect syntax errors, it's external scripts. error
event implies script couldn't downloaded, not syntax errors.
Comments
Post a Comment