To ensure the quality of the project, the script file that is dynamically loaded on the page should be retried if the loading fails (based on the actual situation ).
How can I check whether the script file fails to be loaded? The onerror brother came out of my mind without hesitation, so I wrote the following:Code
VaRScript = Document. createelement ('script'); Script. onerror=Function(EVT) {console. Log ('File loaded error');};Script. SRC= 'HTTP: // www.cnblogs.com/test.js'; Document. getelementsbytagname ('Head') [0]. appendchild (SCRIPT );
Open chrome and try to run it without any pressure. Can the oneror event of the script be captured on the window object? So I tried again:
Window. onerror =Function(EVT) {console. Log ('Error');};VaRScript = Document. createelement ('script'); Script. SRC= 'HTTP: // www.cnblogs.com/test.js'; Document. getelementsbytagname ('Head') [0]. appendchild (SCRIPT );
Okay, chrome Junhua Lili ignored me, for example:
Is there any difference in browser processing? As a result, Google, whose service quality is not very stable recently, was launched. Enter the Keyword: "script onerror detection"
At the top of the list are brother Zheng Mei'sArticle: Script onerror event Support Situation Investigation (Click here)
Destroy three views:Onerror event of script, IE6 ~ Neither opera11 nor 8 is supported.(Naked eye detection, true)
It seems that the browser mentioned above can only adopt roundabout tactics. SetTimeout is an omnipotent plaster, so it is instinct to reject as much rejection as possible (just irrational rejection ..)
One idea is the object detection method.
Function Loadjs (URL, OBJ ){ VaR Script = Document. createelement ('script' ); Script. onreadystatechange = Script. onerror = Function (){ If (! This . Readystate | (( This . Readystate = 'loaded' | This . Readystate = 'complete ')&&!Window [OBJ]) {console. Log ( 'File loaded error' ) ;}}; Script. SRC = URL; document. getelementsbytagname ( 'Head') [0 ]. Appendchild (SCRIPT);} loadjs ( 'Http: // www.cnblogs.com/test.js', 'feeds '); // Assume that the target script contains the feeds object.
The above is just one of the possible ideas. Other measures may be taken based on the specific scenario.