document.createElement("script") 同步 [英] document.createElement("script") synchronously

查看:38
本文介绍了document.createElement("script") 同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以同步调用 .js 文件然后立即使用它?

Is it possible to call in a .js file synchronously and then use it immediately afterward?

<script type="text/javascript">
    var head = document.getElementsByTagName('head').item(0);
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', 'http://mysite/my.js');
    head.appendChild(script);

    myFunction(); // Fails because it hasn't loaded from my.js yet.

    window.onload = function() {
        // Works most of the time but not all of the time.
        // Especially if my.js injects another script that contains myFunction().
        myFunction();
    };
</script>

这是简化的.在我的实现中,createElement 的东西在一个函数中.我想在函数中添加一些可以检查某个变量是否在返回控制之前实例化的东西.但是仍然存在一个问题,当包含来自我无法控制的另一个站点的 js 时该怎么办.

This is simplified. In my implementation the createElement stuff is in a function. I thought about adding something to the function that could check to see if a certain variable was instantiated before returning control. But then there is still the problem of what to do when including js from another site that I have no control over.

想法?

我现在接受了最佳答案,因为它很好地解释了正在发生的事情.但是,如果有人对如何改进这一点有任何建议,我对他们持开放态度.这是我想做的一个例子.

I've accepted the best answer for now because it gives a good explanation for what's going on. But if anyone has any suggestions for how to improve this I'm open to them. Here's an example of what I'd like to do.

// Include() is a custom function to import js.
Include('my1.js');
Include('my2.js');

myFunc1('blarg');
myFunc2('bleet');

我只是不想过多地了解内部结构,而只想说:我希望使用这个模块,现在我将使用它的一些代码."

I just want to keep from having to know the internals too much and just be able to say, "I wish to use this module, and now I will use some code from it."

推荐答案

您可以创建带有onload"处理程序的

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆