[英]Script tag injection with synchronous execution
I have to add a script tag via some JavaScript and have it execute in full as the later statements rely on it. 我必须通过一些JavaScript添加脚本标签,并使其完全执行,因为后面的语句依赖它。
<html> <head> <title>Injecting Script Tags</title> </head> <body> <h1>Injecting Script Tags</h1> <script> console.log('starting'); var newScriptTag = document.createElement('script'); newScriptTag.src = 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js'; newScriptTag.type = 'text/javascript'; document.head.appendChild(newScriptTag); try { var now = moment().format('HH:mm'); console.log(`moment loaded. The time is ${now}`); } catch (e) { console.log(`Moment not loaded: ${e}`); } </script> </body> </html>
As the snippet above shows, the moment()
isn't available on the statement after the tag insertion. 如上面的代码片段所示,插入标签后,
moment()
在语句中不可用。
I think it could be done with eval(...)
, but that option isn't popular. 我认为可以用
eval(...)
,但是该选项并不受欢迎。
use onload event 使用onload事件
<html> <head> <title>Injecting Script Tags</title> </head> <body> <h1>Injecting Script Tags</h1> <script> console.log('starting'); var newScriptTag = document.createElement('script'); newScriptTag.src = 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js'; newScriptTag.type = 'text/javascript'; newScriptTag.onload = function(){ try { var now = moment().format('HH:mm'); console.log(`moment loaded. The time is ${now}`); } catch (e) { console.log(`Moment not loaded: ${e}`); } }; document.head.appendChild(newScriptTag); </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.