如何在没有jquery的情况下检查浏览器中的脚本元素加载事件 [英] how to check the script element load event accross browser without jquery

查看:185
本文介绍了如何在没有jquery的情况下检查浏览器中的脚本元素加载事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须做跨域的ajax,所以我尝试了jsonp。

I have to do the cross-domain ajax,so I try the jsonp.

然后我将不得不添加脚本元素dynamiclly到页面,但是我无法检查它的状态。

Then I will have to add the script element dynamiclly to the page,however I can not check its status.

在firefox / chrome / ie8 +我可以使用

In firefox/chrome/ie8+ I can use the

script.onLoad=function(){}
script.onError=function(){}

我也试过

script.onreadystatechange=function(){}

in ie< 8。

in ie<8.

但它在ie< 8中不起作用。

But it does not work in ie<8.

如何使它工作?

顺便说一句,我想使用原生的javascript,所以不要告诉我使用jQuery或其他任何东西。

BTW,I want to make it using the native javascript,so do not tell me using the jQuery or anything else.

更新:

事实上,我从服务器请求的脚本不是库,它只是一行的javascript代码(jsonp)。所以我不能用计时器来检查。

In fact,the script I request from server is not a library,it is just one-line javascript code (the jsonp). So I can not using the timer to check.

推荐答案

加载在HTML5中引入了脚本元素的事件,之前它只适用于框架集和正文元素(尽管大多数浏览器也为img元素实现了它)。因此,如果您想支持早期的浏览器,您需要具有创造性。

The load event for script elements was introduced in HTML5, prior to that it was only available for frameset and body elements (though most browsers also implemented it for img elements too). So if you want to support earlier browsers you'll need to be creative.

一种解决方案是在脚本顶部放置一个函数调用来表示脚本已被加载,因为浏览器不应该在脚本中执行任何代码,直到它被完整加载。

One solution is to put a function call at the top of the script to say that the script has been loaded, as the browser should not execute any code in the script until it's loaded in its entirety.

另一个是插入第二个脚本我是在假定第二个不会执行第二个函数或标志之后立即加载函数或标志,直到第一个加载并执行。

Another is to insert a second script with the "I'm loaded" function or flag immediately after the first in the presumption that the second will not be executed until the first has been loaded and executed.

这篇关于如何在没有jquery的情况下检查浏览器中的脚本元素加载事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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