Understanding how Greasemonkey runs user scripts - javascript

I'm learning Greasemonkey with the hopes of making some improvements to a webpage.
I think I have a good grasp of JavaScript, but I don't understand at what point in the rendering of the document the Greasemonkey user script is executed.
For instance, what if there is JavaScript natively inside the document that inserts some elements to the page. I want my Greasemonkey script to run only after that JS completes.
Let's say this is the document that I'm trying to modify with Greasemonkey
<html>
<script>
//insert a button with id="mybutton"
</script>
</html>
I want the <script> code to complete before my Greasemonkey script is run, because I want to alter its background color.

Greasemonkey runs at the DOMContentLoaded event by default. This means that everything will be in the page except for possibly large images and stuff added by some javascripts (scripts that fire on the load event or that AJAX-in content).
If you want to wait until even large media has loaded and "onload" scripts have run, use:
window.addEventListener ("load", Greasemonkey_main, false);
function Greasemonkey_main () {
//***** PUT YOUR GREASEMONKEY CODE HERE.
}
Do not use unsafeWindow.onload = function(){ ... } or window.onload = function() { /* logic here */ } as others have suggested. These are not only poor practice/won't work in GM, but the unsafeWindow is an unnecessary security risk in this case.
However, dealing with JS-added content:
Since you indicated that the node you care about is added by javascript, waiting for the load event will often not work. JS can add, remove or edit nodes at any time.
The best approach in cases like these is to poll for the element you are interested in ("#mybutton"). See this answer to "Fire Greasemonkey script on AJAX request".

Related

Order of DOM Execution Issue

I have some JavaScript in the HEAD tag that dynamically inserts an asynchronously loading script tag before the last script on the page (that has been currently parsed). This dynamically included script tag contains JavaScript that needs to parse the DOM after the DOM is available, but before all images AND script tags have been loaded in. It's important that the JavaScript starts executing before all JS has been loaded in, because if there is a hanging script, this would lead to a bad user experience. This means I can't wait for the DOMContentLoaded event to fire. I don't have any flexibility as to where I place the first bit of JavaScript that is dynamically including the script tag.
My question is, is it safe for me to start parsing through the DOM right away, without waiting for the DOMContentLoaded event? If not, is there a way for me to do this without waiting for the DOMContentLoaded event?
...JavaScript in the HEAD ... dynamically inserts an asynchronously loading script tag before the last script on the page...
I'm assuming the loader script is inline, meaning that the highlighted bit actually refers to the "current" script element i.e. the loader. This happens since only the html preceding the loader script tag has been parsed and interpreted, so the inserted script tag is actually still in the head and not at the bottom of the page. So the target script is limited to performing DOM operations on preceding elements only, unless you wrap the code into a DOM ready callback... which is what you're trying to avoid in the first place!
Basically you want to load all html so that the page is visible/scannable, start loading images/stylesheets (which occurs in non-blocking threads) and then load any javascript. One approach is to put your target script at the bottom of the page, just pick their order correctly (interactivity first, enhancements second, third party analytics/social media integration/anything else super-heavy last) and adjust for your needs. Technically it still blocks the page load, but there are only scripts left at the bottom of the page anyway (and since they are at the bottom, you would be able to directly manipulate DOM as soon as they're loaded, minus some IE7 quirks).
There is a relevant rant/overview I like to link to that provides decent examples and some timing trivia on use and abuse of DOM ready callbacks, as well as the "other side of the story" on why stellar performance could be of lower value than a sane dependency management framework. The subject of latter is far too broad to be exhausted in one answer, but something like requirejs documentation should give you a fair idea of how the pattern works.
Perhaps another pattern for to consider is building an SPA - single page application which leverages asynchronous access to content chunks rather than the "traditional" navigating between complete pages. The pattern comes with an underestimated but rather significant performance benefit from not having to parse and re-execute shared javascript on every page, which would also address your (valid) concern about third-party js performance. After all, just a good caching policy would do wonders for loading time, but poor javascript code or massive frameworks' execution overhead remains.
Update: Figured this out. With your specific scenario in mind (i.e. no control over markup per se, and wanting to be the last script to execute), you should wrap the insertion of the async script element into DOM into a 0ms setTimeout callback:
setTimeout(function(){
//the rest is how GA operates
var targetScript = document.createElement('script');
targetScript.type = 'text/javascript';
targetScript.async = true;
targetScript.src = 'target.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(targetScript, s);
}, 0);
Due to the single-threaded nature of the environment, js setTimeout callback is basically added to a queue for 0ms-delayed execution as soon as the thread is no longer busy (more thorough explanation here). So the browser isn't even aware of the need to load, let alone execute, the target script until after all "higher priority" code has been completed! And since DOM is operational when the script tag is being added, you will not have to check for it explicitly in the target script itself (which is handy for when it's loaded "instantly" from cache).
The behavior of the following techniques make it safe to parse DOM ...
Using window load or DomContentLoaded event
Declare or inject your script at the bottom of the page
Place "async" attribute on your script tag
or doing this:
<script>
setTimeout(function(){
// script declared inside here will execute after the DOM is parsed
},0);
</script>
Also, these will NOT BLOCK the page loading in DOM.
There is no need to call the DomContentLoaded event when declaring script below any DOM you are depending on UNLESS you are needing to do size calculations or positioning as images/video will change the sizing of things if width/height is not specified.
Here is some scenarios where this works.
DEPENDENT DOM IS ABOVE
<script src="jquery.js"></script>
<script>
$('mydom').slideDown('fast');
</script>
or try this:
<script>
// won't fart
setTimeout(function(){ console.log(document.getElementById('mydom').innerHTML); },0);
</script>
DEPENDENT DOM IS BELOW or ABOVE (dont' matter)
Here's my little test for you to see setTimeout working as its one of those strange things I didn't notice until recently so its nice to see a working example of it.
http://jsfiddle.net/FFLL2/
Yes, you should wait for the user agent to tell you that the DOM is loaded.
However, there is more than one way to do so.
There is a difference between onreadystatechange to interactive and DOMContentLoaded.
According http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html
the first thing the user agent does, after stopping parsing the document, is setting the
document readiness to "interactive".
The user agent does not wait for scripts to be loaded.
When the document readiness changes, the user agent will fire readystatechange at the Document object.
So if the scripts you are worrying about are non-inline, you might hook up with readystatechange.
Talking about cross-browser: This is the spec.
I strongly advise you to fully read the following article which delves in detail into mysteries of script loading and actual DOM readiness and when is it safe to do what with what, also taking into account browser disrepancies.
http://www.html5rocks.com/en/tutorials/speed/script-loading/

Javascript: accessing DOM before document.onload

I have a page which has document.body.onload=function(){...} but this is suffering delays because the document also contains external <img> tags etc; onload seems to be only getting fired after these external sites have delivered some kind of response.
I put the code in onload because I thought the DOM tree wasn't fully available until then (e.g. document.getElementById(x) might return null if it is called too soon).
Is there an event which triggers after everything in the DOM is accessible, but before everything has been loaded?
You can just place your <script> tag at the end of the body since the html is parsed in sequence.
Additionally, you could look at jquery's document.ready. Even if you don't want to use jquery, you can have a look at how they handle it. ready does exactly what you're asking for.
Sure you can:
Maybe you have two options:
1)
by using jQuery:
with $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads.
2)
DOMContentLoaded
Reference: https://developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded
function checkDom(yourFunc)
{
window.addEventListener('DOMContentLoaded', yourFunc);
}
You should consider if you really need the whole document loaded. As long as your libraries are already loaded and the DOM nodes you are interested in are on the page, you can act immediately. This sort of code makes a page "come alive" much faster than one that waits for every last resource to load:
<form name="foo">
<!-- ... -->
</form>
<script>
var form = new My.FormWidget(document.forms.foo);
</script>
This has the added benefit of forcing you to encapsulate logic in the FormWidget (you should want to keep an "inline" script like that as brief as possible).

Run JavaScript function when the DOM is "ready"?

I'm using a JavaScript upload script that says to run the initialize function as soon as the DOM is ready. I currently have it working just fine with either a call to the function with body.onload or directly after the function is defined. The function builds some HTML in a placeholder div that acts as the file uploader tool.
My question is what is the best practice here? Since it works for now, why would the instructions say to run the init function as soon as the DOM is ready? Should I be adding a <script> tag directly after the placeholder DIV for example?
<script>
window.addEventListener("DOMContentLoaded", function() {
// do stuff
}, false);
</script>
You do that so you know all the parsed elements are available in the DOM etc.
The easiest solution is using jQuery and its $(document).ready(function() { .... }); function. Instead of .... you put your own code.
Note that it basically does the same thing #Shadow2531 suggested, but also works in old browsers not supporting that event.
The DOM is usually ready before onLoad runs. onLoad only runs after everything loads - external scripts, images, stylesheets, etc.
But the DOM, i.e. the HTML structure is ready before that. If you run the code at the bottom of the page (or after the parts of the page the script works with) that will work fine as well.
In 2015 you have two options with modern browsers:
document.onload
this fires when the document is loaded, but other resources (most notably images) have not necessarily finished loading.
window.onload
this fires when the document is loaded, AND all other resources (again, most notably images) are loaded.
Both of the above events would be better utilized with window.addEventListener() of course, as multiple listeners would be allowed.
You could also just move the <script> to the bottom of your page like this:
<html>
<body>
<main></main>
<script>
// code
</script>
</body>
</html>
As you probably know you should not run init functions before the DOM is fully loaded.
The reason you must run the init function as soon as the DOM is ready, is that once the page has loaded the user starts hitting buttons etc. You have to minimize the small inavoidable gap where the page is loaded and the init-functions haven't run yet. If this gap gets too big (ie. too long time) your user might experience inappropiate behaviour... (ie. your upload will not work).
Other users have provided fine examples of how to call the init function, so I will not repeat it here... ;)
Get jQuery and use the following code.
$(document).ready(function(){
// Do stuff
});
var Tette =
{
init: function()
{
/* Your HTML code */
}
};
Core.start(Tette);
You can try in this code, registering "Core.start(your object)" on the last line of the script. This is a way to load in safety your functions after the DOM loading.

Why call $.getScript instead of using the <script> tag directly?

I don't understand the reason for replacing this:
<script src="js/example.js"></script>
with this:
$.getScript('js/example.js', function() {
alert('Load was performed.');
});
Is there a particular reason to use the jQuery version?
The only reason I can think of is that you get the callback when the script is loaded. But you can get that callback using a script tag, too, by using the load event (or on really old IE, onreadystatechange).
In contrast, there are several negatives to doing it this way, not least that getScript is subject to the Same Origin Policy, whereas a script tag is not.
Even if you need to load a script dynamically (and there are several reasons you might need to do that), frankly unless you really need the callback, I'd say you're better off just loading the script by adding a script tag:
$('head:first').append("<script type='text/javascript' src='js/examplejs'><\/script>");
(Note: You need the otherwise-unnecessary \ in the ending tag in the above to avoid prematurely ending the script tag this code exists within, if it's in an inline script tag.)
script tags added in this way are not subject to the Same Origin Policy. If you want the load callback, then:
$("<script type='text/javascript' src='js/examplejs'><\/script>")
.on("load", function() {
// loaded
})
.appendTo('head:first');
(As I said, for really old IE, you'd have to do more than that, but you shouldn't need to deal with them these days.)
I can think of three reasons you might use the jQuery form:
You want all of your script declarations at the top of your document, but you also know that placing script declarations there forces the browser to download them in their entirety before proceeding further in the page rendering process. This can introduce measurable delay. The jQuery form will schedule the script loads until after the document is finished downloading, similar to the effect of placing all of your <script> tags at the end of the document, only without the syntactic weirdness.
The <script> mechanism is not available to scripts that do not live in the HTML document itself; that is, if a script included on the page with <script> wants to load a script, it has no option but to use a JavaScript-based approach, such as calling the jQuery function.
The jQuery form allows notification of the script's successful execution, in the form of a supplied callback function.
No need to do that..
You do that if you want to load the script dynamically (when needed, and not from the beginning)
The script might depend on jQuery, so it would be a way to prevent the browser trying to load it if it hasn't loaded jQuery.
There are a number of reasons that jQuery might not load, from a simple network failure to a CDN not being whitelisted by a NoScript user.
maybe to control when a script is loaded? On a javascript heavy page, it may be worth waiting to load some things that are non essential until after essential things are loaded.

Lazy loading the addthis script? (or lazy loading external js content dependent on already fired events)

I want to have the addthis widget available for my users, but I want to lazy load it so that my page loads as quickly as possible. However, after trying it via a script tag and then via my lazy loading method, it appears to only work via the script tag. In the obfuscated code, I see something that looks like it's dependent on the DOMContentLoaded event (at least for Firefox).
Since the DOMContentLoaded event has already fired, the widget doesn't render properly. What to do?
I could just use a script tag (slower)... or could I fire (in a cross browser way) the DOMContentLoaded (or equivalent) event? I have a feeling this may not be possible because I believe that (like jQuery) there are multiple tests of the content ready event, and so multiple simulated events would have to occur.
Nonetheless, this is an interesting problem because I have seen a couple widgets now assume that you are including their stuff via static script tags. It would be nice if they wrote code that was more useful to developers concerned about speed, but until then, is there a work around? And/or are any of my assumptions wrong?
Edit:
Because the 1st answer to the question seemed to miss the point of my problem, I wanted to clarify the situation.
This is about a specific problem. I'm not looking for yet another lazy load script or check if some dependencies are loaded script. Specifically this problem deals with
external widgets that you do not
have control over and may or may not
be obfuscated
delaying the load of the
external widgets until they
are needed or at least, til
substantially after everything else
has been loaded including other deferred elements
b/c of the how
the widget was written, precludes
existing, typical lazy loading
paradigms
While it's esoteric, I have seen it happen with a couple widgets - where the widget developers assume that you're just willing to throw in another script tag at the bottom of the page. I'm looking to save those 500-1000 ms** though as numerous studies by Yahoo, Google, and Amazon show it to be important to your user's experience.
**My testing with hammerhead and personal experience indicates that this will be my savings in this case.
The simplest solution is to set parameter domready to 1 when embedding addthis script into your page. Here is an example:
<script type="text/javascript"
src="http://s7.addthis.com/js/250/addthis_widget.js#username=addthis&domready=1">
</script>
I have tested it on IE, Firefox, Chrome, and Safari, and all worked fine. More information on addthis configuration parameters is available here.
This code solves the problem and saves the loading time that I was looking for.
After reading this post about how most current js libraries implement tests for a dom loaded event. I spent some time with the obfuscated code, and I was able to determine that addthis uses a combination of the mentioned doscroll method, timers, and the DOMContentLoaded event for various browsers. Since only those browsers dependent on the DOMContentloaded event would need the following code anyway:
if( document.createEvent ) {
var evt = document.createEvent("MutationEvents");
evt.initMutationEvent("DOMContentLoaded", true, true, document, "", "", "", 0);
document.dispatchEvent(evt);
}
and the rest depend on timers testing for existence of certain properties, I only had to accommodate this one case to be able to lazy load this external JS content rather than using the static script tags, thus saving the time that I was hoping for. :)
Edit: If the goal is simply to have your other contetn load first, try putting the <script> tags near the bottom of your page. It will still be able to catch the DOMContentLoaded and the content that comes before will be loaded before the script.
Original:
in addition to loading on DOMContentLoaded, you could have it load if a certain var is set true. e.g.
var isDOMContentLoaded = false;
document.addEventListener("DOMContentLoaded",function() { isDOMContentLoaded = true; }, false);
then add to the other script file
if (isDOMContentLoaded) loadThisScript();
Edit in response to comments:
Load the script, and run the function that the DOMContentLoaded listener fires. (read the script if you're not sure what function is being called ).
e.g.
var timerID;
var iteration=0;
function checkAndLoad() {
if (typeof loadThisScript != "undefined") {
clearInterval(timerID);
loadThisScript();
}
iteration++;
if (iteration > 59) clearInterval(timerID);
}
var extScript = document.createElement("script");
extScript.setAttribute("src",scriptSrcHere);
document.head.appendChild(extScript);
timerID = setInterval(checkAndLoad,1000);
The above will try once a second for 60 seconds to check if the function you need is available, and, if so, run it
AddThis has a section on how to load their tools asynchronously.
Current 'best' solution:
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=[YOUR PROFILE ID]" async="async"></script>

Categories

Resources