How to execute content script after the page is loaded completely
Probably the page loads its content dynamically though AJAX, so the elements you want to find may be still not loaded when the document state is ready. Even if some part of content is loaded on start, more content may come later. To solve this issue correctly I'd recommend you the MutationObserver techniques. I used it in my Chrome extension to inject the 'Favorite' button to each Facebook post and it worked perfectly.
See the code sample:
var obs = new MutationObserver(function (mutations, observer) {
for (var i = 0; i < mutations[0].addedNodes.length; i++) {
if (mutations[0].addedNodes[i].nodeType == 1) {
$(mutations[0].addedNodes[i]).find(".userContentWrapper").each(function () {
injectFBMButton($(this));
});
}
}
injectMainButton();
});
obs.observe(document.body, { childList: true, subtree: true, attributes: false, characterData: false });
Without jQuery you can do this defining a callback function on the page load event. You can do it this way :
var loadfunction = window.onload;
window.onload = function(event){
//enter here the action you want to do once loaded
if(loadfunction) loadfunction(event);
}
Or this way :
window.addEventListener("load", function load(event){
window.removeEventListener("load", load, false); //remove listener, no longer needed
//enter here the action you want to do once loaded
},false);