Stop all scripts in a page from loading - javascript

I've been trying to get this code working in Google Chrome but I can't seem to be able to stop server requests from "removed" scripts from happening.
What I'm trying to do is remove all scripts in a page, the code below removes the scripts from the DOM but they still load and execute.
Code:
document.addEventListener("DOMContentLoaded", function(){
var e2 = document.getElementsByTagName("script");
for(var i = e2.length; i--; e2[i].parentNode.removeChild(e2[i]));
});​
Any ideas?

Scripts are blocking, so any script tag that appears before the closing body tag is downloaded, parsed and executed before the DOMContentLoaded event.
You could always take a look at async or defer attributes on your script tags, but you'd still be guessing if they have been executed or not by the time your DOMContentLoaded listeners gets executed.
You should really try to look for an alternative method to achieve what you want to accomplish here. Might I ask what you're trying to do?

Related

JavaScript Will Not Load After DOM

I'm having trouble getting my JS to run after all my content has loaded. Right now on the site Im working on: http://hsvgridproject.com, the grid will not load the first time a user visit the site and needs a hard refresh before it will work. I believe I need to use a window.onload function of some sort but as I am still learning Java I'm not sure how to implement it into my project without breaking the code.
The script for the grid on homepage has a window tag surrounding it already (credit Codrops):
(function(window) {
Please let me know if you need more info. Thank you!
It's probably not working because you're executing your script before the DOM is fully loaded.
To ensure it's executed after the DOM is fully loaded, either move the script tag which executes your code right before the closing tag of the body element or use DOMContentLoaded event like this:
document.addEventListener("DOMContentLoaded", function(event) {
// execute your code
});

When to use "window.onload"?

In JavaScript, when I want to run a script once when the page has loaded, should I use window.onload or just write the script?
For example, if I want to have a pop-up, should I write (directly inside the <script> tag):
alert("hello!");
Or:
window.onload = function() {
alert("hello!");
}
Both appear to run just after the page is loaded. What is the the difference?
The other answers all seem out of date
First off, putting scripts at the top and using window.onload is an anti-pattern. It's left over from IE days at best or mis-understandings of JavaScript and the browser at worst.
You can just move your scripts the the bottom of your html
<html>
<head>
<title>My Page</title>
</head>
<body>
content
<script src="some-external.js"></script>
<script>
some in page code
</script>
</body>
</html>
The only reason people used window.onload is because they mistakenly believed scripts needed to go in the head section. Because things are executed in order if your script was in the head section then the body and your content didn't yet exist by definition of execute in order.
The hacky workaround was to use window.onload to wait for the rest of the page to load. Moving your script to the bottom also solved that issue and now there's no need to use window.onload since your body and content will have already been loaded.
The more modern solution is to use the defer tag on your scripts but to use that your scripts need to all be external.
<head>
<script src="some-external.js" defer></script>
<script src="some-other-external.js" defer></script>
</head>
This has the advantage that the browser will start downloading the scripts immediately and it will execute them in the order specified but it will wait to execute them until after the page has loaded, no need for window.onload or the better but still unneeded window.addEventListener('load', ...
window.onload just runs when the browser gets to it.
window.addEventListener waits for the window to be loaded before running it.
In general you should do the second, but you should attach an event listener to it instead of defining the function. For example:
window.addEventListener('load',
function() {
alert('hello!');
}, false);
Here's the documentation on MDN.
According to it:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
Your first snippet of code will run as soon as browser hit this spot in HTML.
The second snippet will trigger popup when the DOM and all images are fully loaded (see the specs).
Considering the alert() function, it doesn't really matter at which point it will run (it doesn't depend on anything besides window object). But if you want to manipulate the DOM - you should definitely wait for it to properly load.
That depends on if you want it to run when the script element is encountered or if you want it to run when the load event fires (which is after the entire document (including such things as images) has loaded).
Neither is always right.
In general, however, I'd avoid assigning functions directly to onload in favour of using addEventListener (with compatibility libraries if I needed to support older browsers).
The reason for waiting for the DOM to be loaded is so that you can target any elements that load after your script. If you're just creating an alert, it doesn't matter. Let's say, however, you were targeting a div that was in your markup after your script, you would get an error if you don't wait until that piece of the DOM tree to load.
document.ready is a great alternative to window.onload if you're using jQuery.
See here: window.onload vs $(document).ready()
You have three alternatives:
Directly inside the script tag runs it as soon as it is parsed.
Inside document.addEventListener( "DOMContentLoaded", function(){}); will run it once the DOM is ready.
Inside window.onload function(){}) will run as soon as all page resources are loaded.

Understanding how Greasemonkey runs user scripts

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".

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.

Inserting a script dynamically in the DOM

I'm trying to understand why this code doesn't work and the alert output is just blank.
<script type="text/javascript">
(function() {
...
var s = document.getElementsByTagName('script')[0]; alert(s.innerHTML);
s.parentNode.insertBefore(res, s);
...
})();
</script>
It should add res before s if I'm not wrong. That's what I specifically need, as I tried to append it to body and it's added successfully (after doing that though I have to run some code inside this function, so if the script is not loaded before it, such code will error).
This function should run when document is loaded or is that the problem? In particular, the getElementsByTagName function seems to not return anything.
Thanks to everyone.
You cannot run this type of code before the document is loaded. This code has to be loaded before it can be run (see the circular argument here). And, by then, much of the rest of the document has been loaded. You can dynamically load scripts AFTER the document has been loaded. If you need a script loaded before other scripts, then you either have to put them all in the document statically in the order you need them to be run or you need to add them all dynamically in the order you need them to run and you will need to keep track of completion of one load before loading the next.
If you care to describe the broader problem you're trying to solve, we can probably suggest a more elegant solution than what you are pursuing.

Categories

Resources