Opera中的JavaScript范围问题? [英] JavaScript scope issue in Opera?

查看:79
本文介绍了Opera中的JavaScript范围问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于小部件的HTML + JavaScript块,人们可以将其复制或粘贴到其HTML页面一次或多次.该代码块检查DOM中是否已存在外部JavaScript文件,如果没有,则将其加载,如下所示:

I have a widget-like block of HTML+JavaScript that people can copy/paste into their HTML-page one or multiple times. That block checks if an external JavaScript file is already in the DOM, and loads it if not, something like this:

(function(){
  d = document;
  if (!d.getElementById('ex-scr')) {
    scr = d.createElement('script');
    scr.async = true;
    scr.id = 'ex-scr';
    scr.src = 'external.js';
    d.getElementsByTagName('head')[0].appendChild(scr)
  }
})();

外部JavaScript文件检查HTML页面中的小部件实例(使用getElementsByClassName),并对这些实例进行填充,就像这样;

The external JavaScript-file checks the HTML-page for instances of the widget (using getElementsByClassName) and does stuff with those instances, kind of like this;

for (var i=0;i<document.getElementsByClassName('target').length;i++) {
 document.getElementsByClassName('target')[i].style.borderStyle="solid";
}

可以在 http://futtta.be/opera_enigma.html这在Firefox(3.6& 4b),Chrome(5& 6)和Safari中完美运行,但在Opera(经最新版本10.61测试)中无法正常工作:无论有多少部件" (带有class='target'的div)存在,Opera仅作用于第一个,因为显然nodeList仅包含1个条目(长度为1而不是2或3或...).

This works perfectly in Firefox (3.6 & 4b), Chrome (5 & 6) and Safari, but does not work as expected in Opera (tested with most recent version, 10.61): no matter how many 'widgets' (divs with class='target') are present, Opera only acts on the first one because apparently the nodeList only contains 1 entry (length is 1 instead of 2 or 3 or ...).

如果在小部件的javascript中调用了使用window.onload加载外部脚本的函数,问题就消失了,但是我希望我的小部件尽快激活(不干扰页面的其余部分,因此异步的东西).

The problem goes away if in the widget's javascript I call the function to load the external script with window.onload, but I'd like my widget to activate as soon as possible (without interfering with the rest of the page, hence the asynchronous stuff).

所以我的问题;我的代码中有没有Firefox,Safari和Chrome浏览器忽略的错误?这是Opera中的错误吗?如何使Opera表现良好?

So my questions; is there a bug in my code which Firefox, Safari and Chrome ignore? Is this a bug in Opera? How can I get Opera to behave?

推荐答案

如果在小部件的javascript中调用了使用window.onload加载外部脚本的函数,问题就消失了

The problem goes away if in the widget's javascript I call the function to load the external script with window.onload

我认为那是您的问题.在脚本文件中执行getElementsByClassName时,尚不能保证DOM完全存在.您必须等到DOMreadyloaded事件后,才能在此处创建可靠的行为.

I think that's your problem right there. When the getElementsByClassName is executed in your script file, the DOM is not yet guaranteed to be completely present. You won't be able to create reliable behaviour here without waiting until the DOMready or loaded event.

这篇关于Opera中的JavaScript范围问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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