it executes after the page loads and that's not fast enough for what I'm trying to accomplish.
The onload event will wait for the page to be loaded - depending on what your page is doing that may be a signifiant delay.
Scripts in the head aren't what you want
A script which modifies the content of the page must wait for the content it wants to modify to exist. That doesn't mean waiting for document ready though.
So, for example, this will not work:
<html>
<head>
<script>
function replaceLinks() {
var links = document.querySelectorAll('.restore a:link');
for (var i = 0; i < links.length; i++) {
if (/\.(jpg|gif|png|jpe?g)$/.test(links[i].href)) continue;
links[i].innerHTML = '<a href="/register.php" class="guestbutton">DOWNLOAD VIDEO</a>';
links[i].href = 'register.php';
}
}
replaceLinks(); // run the replace function
</script>
</head>
<body>
<a class="restore" href="#">A link</a>
</body>
</html>
It won't work because when replaceLinks is called the links it should modify don't exist yet.
Put your script at the end of the page
It is a generally-held best practice to put scripts at the end of the page. I.e. for the example in the question like so:
<html>
<head>
</head>
<body>
<a class="restore" href="#">A link</a>
<script>
function replaceLinks() {
var links = document.querySelectorAll('.restore a:link');
for (var i = 0; i < links.length; i++) {
if (/\.(jpg|gif|png|jpe?g)$/.test(links[i].href)) continue;
links[i].innerHTML = '<a href="/register.php" class="guestbutton">DOWNLOAD VIDEO</a>';
links[i].href = 'register.php';
}
}
replaceLinks(); // run the replace function
</script>
</body>
</html>
In this way, the content it wants to modify already exists when it runs, and it runs as soon as the script tag is parsed.
Note that the function does not need to be in the same script block, it simply needs to be defined before being called (it could be declared in the head - but there's no reason to do that).
However, don't use javascript for that
There are a number of problems with what's proposed in the question though:
- The page's original contents will be displayed first, and then replaced with "DOWNLOAD VIDEO" links. I.e. similar to FOUC
- Users can access the links by either reading the source or simply disabling javascript
As such, it would be much more appropriate to not use javascript for this task and modify the contents on the server before sending to the client.
replaceLinks()to accomplish?replaceLinks()be able to replace before the page loads?<script>tag after each element you want to modify.<script> function replaceLinks() { var links = document.querySelectorAll('.restore a:link'); for (var i = 0; i < links.length; i++) { if (/\.(jpg|gif|png|jpe?g)$/.test(links[i].href)) continue; links[i].innerHTML = '<a href="/register.php" class="guestbutton">DOWNLOAD VIDEO</a>'; links[i].href = 'register.php'; } } </script>