最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript only works when with alerts - Stack Overflow

programmeradmin4浏览0评论

The following code loads a youtube vidéo in a player.

If I remove the two "alert", it doesn't work anymore...

ytplayer = document.getElementById("ytPlayer");
alert('ok');
if (ytplayer) {
    alert('ok');
    loadVideo(url, start);
}

Can someone help me?

The following code loads a youtube vidéo in a player.

If I remove the two "alert", it doesn't work anymore...

ytplayer = document.getElementById("ytPlayer");
alert('ok');
if (ytplayer) {
    alert('ok');
    loadVideo(url, start);
}

Can someone help me?

Share Improve this question edited Jul 13, 2012 at 15:08 Esailija 140k23 gold badges279 silver badges328 bronze badges asked Jul 13, 2012 at 14:54 user1523891user1523891 2
  • 1 alert's halt the thread of execution in JavaScript until you press OK, so it would point towards some asynchronous behaviour you're not handling correctly. – Matt Commented Jul 13, 2012 at 14:57
  • alert stops execution of JS, your code is running before the time. – loler Commented Jul 13, 2012 at 14:58
Add a ment  | 

4 Answers 4

Reset to default 10

you are probably invoking the code before the page loads. With the alert, js execution stops, allowing the page to load. If this is correct, you need to look into the window.onload callback or possibly document.ready

window.onload = function(){
   // load the vid here
}

Invoke the function after the page has been loaded pletely.

window.onload = function() {
    loadVideo(url, start);
}

I fixed the problem with the following :

ytplayer = document.getElementById("ytPlayer");

if (ytplayer) {
    setTimeout( function() { loadVideo(url, start); }, 1000);
}

Thanks for your answers.

Did you use Ajax Request ?

if YES then put you code that didnt work at the end of

AjaxObject.onreadystatechange = function () {
       if (AjaxObject.readyState == 4) {
           .
           .
           .
           .
           .

      // PUT HERE
        }
   }

then IF NO put your code in function and return false or true

like this

ytplayer = document.getElementById("ytPlayer");
alert('ok');
if (ytplayer) {
    //alert('ok');
    loadVideo(url, start);   
return true;     
}

hope helps

发布评论

评论列表(0)

  1. 暂无评论