简体   繁体   English

外部JavaScript渲染

[英]external javascript rendering

There are two javascript files on a page, both coming from different domains. 页面上有两个JavaScript文件,它们均来自不同的域。 Now the 2nd file is loaded before the 1st as the server response time for the 2nd javascript file is greater than for the first javascript file. 现在,由于第二个javascript文件的服务器响应时间大于第一个javascript文件的服务器响应时间,因此第二个文件在第一个文件之前加载。 The second javascript file depends on some function set in the first javascript file, so it is throwing an error. 第二个javascript文件取决于第一个javascript文件中设置的某些功能,因此会引发错误。

Now my question is: does javascript file ordering take place? 现在我的问题是:javascript文件排序发生了吗? ie do they execute sequentially? 即它们是否顺序执行? If yes, then why is the second javascript file executed first and throws an error 如果是,那么为什么第二个javascript文件首先执行并引发错误

If you have script elements they will execute in the order they are placed, unless you load them programmatically or explicity tell them to load asynchronously with the HTML5 async attribute (which is not supported by IE less than version 10). 如果您具有脚本元素,它们将按照它们的放置顺序执行,除非您以编程方式加载它们或明确地告诉它们使用HTML5 async属性(IE 10之前的版本不支持该属性)异步加载。

It is possible that the scripts themselves have asynchronous behavior inside of them, which could cause the appearance of them executing in the wrong order. 脚本本身内部可能具有异步行为,这可能导致脚本以错误的顺序执行。

If you are loading two scripts via AJAX, then have two functions (one to load each) and call the second one when the first has loaded. 如果要通过AJAX加载两个脚本,则有两个函数(每个都要加载),并在第一个加载后调用第二个。 Like so (below is just an example): 像这样(下面仅是一个示例):

function loadfirstscript()
{
var http = new XMLHttpRequest();
var url = "get_data.php";
http.open("GET", url, true);

http.onreadystatechange = function() {//Call a function when the state changes.
     if(http.readyState == 4 && http.status == 200) {
          //do something here...

          loadsecondscript() //Call the second script
     }
}
http.send(params);
}

Edit: Sorry if this does not answer your question, but I am not too sure what you are asking if this does not answer your question. 编辑:对不起,如果这不能回答您的问题,但是我不太确定您在问什么,如果这不能回答您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM