Periodically testing of elements that are added to the DOM after pageload
I've got a page where you upload videos, those videos are then encoded (much like Youtube). The encoding part can take some time and I want to automatically show the user if encoding is done by periodically polling the encoding status from within the page, if encoding is completed I want to replace the encoding icon with a "play" button so the user can play the video.
开发者_运维百科Because the list of uploaded videos itself is put into the DOM using AJAX (with jQuery) I have trouble wrapping my head around how to do this. I'd like to use jQuery for this, but I don't know if jQuery can do this.
So the steps are as follows
- user uploads a video
- user is returned to a page
- user "folds open" the list of uploaded videos, some encoded some not yet, the encoded ones have play buttons, the unencoded ones have hourglass icons
- user waits until the icons for the not-yet-encoded videos turn into play buttons
- user pushes play button and the movie plays
My problem is only at step 4. The serverside part is all done as well.
Use polling. Set an interval to poll the server (using AJAX) every few seconds to check the status of the encoding job. When the server responds with a "job completed", update your icon in the DOM.
If it were me, I would have the server-side handler respond with the percentage of completion (if that is possible, it would depend on your encoding API).
If the issue is that you don't know how to get the page to poll the server every X seconds, you can do this with javascript using setTimeout(function, milliseconds) and setInterval(function, milliseconds). You put your polling code in the definition for function.
Here's an article with details.
Thanks for the respons about setInterval, that was very helpful in getting me halfway there.
I had another load of problems with the asynchronous nature of jQuery's .get() calls, which I called in a function, and then depending on the result of the .get() call, should return true/false. That does not work if you call an asynchronous function, as far as I discovered at least. That asynchronous function can call another function, which I used to alter the DOM.
My final solution to this problem is as follows. It's a bit hackish and the Javascript doesn't degrade gracefully, but the code is for a prototype system and will only be used in a controlled environment of a handful of computers so Javascript enabling is guaranteed.
About my code: I always display the encoding icon AND the play icon, but hide the icon that is not relevant. The play icon is clickable and gives a popup with the video.
See pastebin for my solution.
精彩评论