@jblumberg , I would definitely look into MutationObservers like dgrobani recommended.
There are a few of problems with the approach you're not using in your pastebin.
- You are polling, which takes unnecessary resources when it should be event driven.
- Any timeout-based approach is sensitive to the speed of the machine and possibly the network. 3 seconds might be enough one time, but not another, and possibly on the same machine at a different point in time
- You wait for a certain selector to appear and then stop listening for it and you execute your code. However, Canvas has started using ReactJS to update pages and it keeps its own virtual DOM, meaning that changes you make to the browser's DOM can be overwritten at any point by render() and then you need to update the browser's DOM that the user is seeing a second or third time. The timeout approach you're using will never catch that and will only update the code once.
MutationObservers fix all of those problems.
- They are event driven, so they happen when a change is made, you don't need to poll looking for it.
- They don't have a timeout, so it doesn't matter if it takes 1.2 seconds or 10 seconds. Once the event happens, it's triggered.
- You can leave them observing and watching for more changes to happen so that you can re-issue your changes if the underlying DOM changes and removes it.
That said, they're not as plug and play as just waiting for an element to appear. Insertions, deletions, attribute changes, (whatever you set it up to observe), are all handled by a single function. That function has to figure out what to do.
If you're just waiting for an element to appear, you can normally just check for the existence of it within the mutation observer and act if it is present. But that won't necessarily catch an update as it may be a different part of the DOM that is updated.
The element you pick to observe has to already be there in the original document (you can't observe a non-existent element) and you want it as close to the item you're trying to watch. It changes from item to item, so it may be different on each page. In your case, you can setup different observers based on the page you're on (I would modify your code to do that anyway) or you can install a blanket one that checks for changes to the id=content div and then acts based on the page that you're on.
There's so much more I could write, but I've got to go pick up the kids right now.