getElementById not working in Google Chrome extension for <embed>

↘锁芯ラ 提交于 2019-12-04 21:13:34

Direct executing DOM related operation in JS is not correct. For example:

default.html

<!DOCTYPE HTML>
<html>
    <head>
    <script type="text/javascript" src="default.js"></script>
    </head>
    <body>
         <a id="Bar" href="#"></a>
    </body>
</html>

default.js

const bar = document.getElementById("Bar");
alert(bar.id);

At this time the DOM content may not be completely loaded yet, and that is why the "bar" may be "NULL".

The correct way to do this is:

default.js

document.addEventListener('DOMContentLoaded', function() {
  const bar = document.getElementById("Bar");
  alert(bar.id);
  });

That is: executing the DOM related operation when the DOMContentLoaded event happens.

"setTimeout" is not the right way because you cannot make sure the DOM content is completely loaded by setting some time delay!

Turns out the problem was with timing. Even though it was inside a jQuery(document).ready(), the getElementById failed because the embed wasn't loaded yet. When I do a setTimeout of a few seconds, the getElementById works.

Works fine for me in chrome 9.

Try this fiddle: http://jsfiddle.net/Ee7mq/

If the console doesn't show the player tag something is wrong with your browser. If it does, something is wrong with your code. To figure out what i'd need to see more of it.

Use defer.

<script defer>...</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!