同步执行脚本标签注入

时间:2019-05-20 14:48:00

标签: javascript html xmlhttprequest eval

我必须通过一些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>

如上面的代码片段所示,在插入标签之后,moment()在语句中不可用。

认为可以用eval(...)完成,但是这种选择并不受欢迎。

1 个答案:

答案 0 :(得分:0)

使用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>