JavaScript Snippets for Fast SEO Analysis

There are times when you want to be able to quickly jump into a webpage and start analyzing the content without the need to rely on a web crawler.

This is where JavaScript snippets have a massive advantage. You can save an arsenal of JavaScript snippets locally in your browser and fire them off at any time, turning you into a sort of John Wick-level SEO analyst.

Contents

Prerequisites

  • Google Chrome Browser: You need to have the Google Chrome web browser installed on your computer.
  • A Web Page: You must have a web page open in your Google Chrome browser.
  • Understanding of Chrome DevTools: DevTools is a built-in feature of Chrome. We’ll be using the “Snippets” feature of DevTools.
  • Light experience using JavaScript: You don’t have to be a pro, but understanding beginner-level concepts is a plus.

Why JavaScript?

Simply put, JavaScript was designed to be executed in web browsers, making it the natural choice for client-side scripting. JavaScript has native browser support, meaning that all major web browsers (Chrome, Mozilla, Safari, Microsoft Edge), can interpret and execute JavaScript code.

Getting Setup for Snippets

Snippets are a great feature introduced by Chrome for web developers who are repeatedly running code in their browser console. Rather than manually writing code or transferring it from local files, Snippets can be saved within your local DevTools instance, sort of like bookmarking a webpage.

To get started:

  1. Navigate to the page you want to analyze
  2. Open Chrome Dev Tools: Mac Cmd + Option + J, Windows/Linux Control+Shift J
  3. Navigate to the Sources Tab
  4. Within Sources, Navigate to >> Snippets
  5. Click + New snippet
  6. Paste or write a snippet within the new snippet
  7. Click the Run button to execute the snippet

Source: https://developer.chrome.com/docs/devtools/javascript/snippets/

Extract Page Content from HTML using JavaScript

Function: This snippet extracts all of the text content within the <body> tag of the page. This includes navigation and footer text. The snippet selector ‘body' can be modified as needed.

I typically extract page content when auditing content density of a page. If most of the page content being extracted is text from the header and footer, then there may be opportunities to improve the SEO performance by adding additional content to the main section of the page.

Use Cases:

  • Analyzing word count
  • Organizing content for optimizations
  • Organizing content for AI
  • Measuring content density
// Modify the selector as needed
const mainBodyElement = document.querySelector('body'); 

const mainTextContent = mainBodyElement.innerText;

// Display the extracted text content in the console
console.log(mainTextContent);

Output:

Extract href Values from Anchor Tags using JavaScript

Function: Extracts all href attribute values from anchor tags from the HTML of a page.

I include this snippet in my toolbox if I want to quickly extract all the href values from a page for deeper analysis. I find this snippet helpful for identifying anchor tags that don’t have proper href values (such as “#” or “javascript:void(0”), or for getting a list of all internal links to crawl.

Use Cases:

  • Analyzing the crawlability of a rendered page
  • Extracting all anchor tag href values
  • Analyzing <a> tags with low-value href values
  • Analyzing link structures of a page
// Get all anchor (a) elements in the HTML document
const anchorElements = document.querySelectorAll('a');

// Create an array to store the href attribute values
const hrefValues = [];

// Use forEach to iterate through the anchor elements and extract the href attribute value
anchorElements.forEach((element) => {
  const href = element.getAttribute('href');
  if (href) {
    hrefValues.push(href);
  }
});

// Convert the href values to a string with line breaks
const hrefString = hrefValues.join('\n');

// Display the extracted href values in the console
console.log(hrefString);

Output:

Extract Image Size Using JavaScript

Function: Target all <img> tags on a webpage and extract the image sizing in KB and MB, depending on the size of the image. The output returns the size of the image along with the image URL.

This snippet is especially useful for getting a quick snapshot of images that may be contributing to page load or performance issues.

Use Cases:

  • Quickly analyze the sizing of images on a page
  • Image size auditing
  • Image file extension auditing
  • Core Web Vitals
// Get all <img> elements on the page
const images = document.querySelectorAll('img');

// Create a function to convert bytes to KB or MB
function formatSize(bytes) {
  if (bytes < 1024) {
    return bytes + ' B';
  } else if (bytes < 1024 * 1024) {
    return (bytes / 1024).toFixed(2) + ' KB';
  } else {
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
  }
}

// Loop through each image and display its size and URL
images.forEach((image, index) => {
  const imageSizeInBytes = image.naturalWidth * image.naturalHeight * 4; // Assuming 4 bytes per pixel (32-bit image)
  const imageSizeFormatted = formatSize(imageSizeInBytes);
  const imageURL = image.src;
  console.log(`Image ${index + 1} Size: ${imageSizeFormatted}`);
  console.log(`Image ${index + 1} URL: ${imageURL}`);
});

Output:

Function: Target all <a> tags from your HTML document and then filters only the links that include the window’s origin (your website) in the href attribute. As a result, this leaves you with an array (count) of all internal links. When the code runs, it will scan your web page and logs the total number of internal links present.

If a webpage returns 0 links, this could possible mean that the page is generating links via JavaScript which can greatly impact the crawlability of a site.

Use Cases:

  • Quickly analyze the count of rendered internal links of a webpage
  • Analyzing the crawlability of a rendered webpage
const internalLinks = Array.from(document.querySelectorAll('a')).filter(link => link.href.includes(window.location.origin));

console.log(`Internal links on this page: ${internalLinks.length}`);

Output:

Measure Page Load Speed with JavaScript

Function: This snippet provides a fast and easy way of measuring the page load speed which is a critical factor in web performance optimization and overall user experience.

The loadTime variable returns the timestamp difference between when the DOMContentLoaded event has finished and when navigationStart beings (when navigation of the document begins). Note, the timestamp does not wait for stylesheets, images, and other sub-resources to finish loading.

Use Cases:

  • Analyze page load across different page-templates
  • Measure page load and its impact on Core Web Vital metrics
  • UX and general performance analyzation and testing
const loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;

console.log(`Page load time: ${loadTime}ms`);

Output:

Extract Page Meta Tags using JavaScript

Function: Extract the content of all meta tags from the HTML document of a page and log to the console as a JavaScript object. This includes meta tags such like the meta description, meta robots, open graph and twitter card meta tags, and any other meta tags found on a webpage.

Use Cases:

  • Quickly reviewing a pages meta tags for new metadata opportunities
  • Audit page meta tags for social media snippets
const metaTags = document.querySelectorAll('meta');
const metaData = {};

metaTags.forEach((tag) => {
  const name = tag.getAttribute('name') || tag.getAttribute('property');
  const content = tag.getAttribute('content');
  if (name && content) {
    metaData[name] = content;
  }
});

console.log('Metadata:', metaData);

Output:

Extract Page Word Count with JavaScript

Function: Analyze the word count within the <body> element of rendered HMTL document. This snippet fetches the entire content of your webpage using the ‘document.querySelector(‘body’).textContent’ syntax. Following this, it splits the content into an array of individual words, through ‘bodyContent.split(/\s+/)’. To filter out potential white spaces, it places a condition for only considering strings with a length greater than ‘0’.

💡Note: the querySelector() method can be updated to extract the word count of any HTML element. If a site uses a main navigation, it may be useful to select a more specific tag to measure the main content of a page.

Use Cases:

  • Quickly analyze word count of a page
  • Use across multiple pages to discover pages with low word count
  • Set a threshold of what is considered “low word count” and use as a guide to update content with low word count
const bodyContent = document.querySelector('body').innerText;
const wordCount = bodyContent.split(/\s+/).filter(word => word.length > 0).length;

console.log('Word count:', wordCount);

Extract Image Alt-Text with JavaScript

Function: Extract all image alt-text along with the corresponding image src attribute. Both the alt-text and URL are then logged into the console, attributed with their respective image number for easier identification.

This JavaScript snippet serves as a useful tool for developers for SEO Page Analysis, Accessibility Testing, and enhancing web scraping techniques.

Use Cases:

  • Audit img tags, and find images with/without alt-text
  • Identify opportunities to add new alt-text or update pre-existing alt-text
  • Advanced web-scraping (headless crawler)
const images = document.querySelectorAll('img');

images.forEach((image, index) => {
  const altText = image.getAttribute('alt');
  const imageURL = image.src;
  console.log(`Image ${index + 1} Alt Text: "${altText}"`);
  console.log(`Image ${index + 1} URL: "${imageURL}"`);
});

Extract Images With and Without Alt-Text with JavaScript

Function: This snippet is a valuable shortcut for efficiently gathering all the images from a rendered web page and categorizing them according to the presence or absence of alt-text. Images with and without alt-text are added to respective arrays, and each array is then logged to the console for easy separation of images with and without alt-text.

Use Cases:

  • Bulk review of all image alt-text
  • Organization of images with/without alt-text
  • Easily identify images missing alt-text from a webpage
  • Optimization opportunities for pre-existing alt-text
const images = document.querySelectorAll('img');
const imagesWithAltText = [];
const imagesWithoutAltText = [];

images.forEach((image) => {
const altText = image.getAttribute('alt');
const imageURL = image.src;

if (altText && altText.trim() !== '') {
imagesWithAltText.push(`Alt Text: "${altText}", Image URL: "${imageURL}"`);
} else {
imagesWithoutAltText.push(`${imageURL}`);
}
});

// Join the arrays with newline characters
const imagesWithAltTextString = imagesWithAltText.join('\n');
const imagesWithoutAltTextString = imagesWithoutAltText.join('\n');

console.log('Images with Alt Text:\n', imagesWithAltTextString);
console.log('Images without Alt Text:\n', imagesWithoutAltTextString);

Visualize Various Alt-Text Lengths Using JavaScript

Function: This snippet is not for the faint of heart, but it’s a cool way to perform some scrappy data visualization within the console. All anchor tags are analyzed, and for each anchor, it retrieves the anchor text and its length. After determining the length, the function represents it visually by repeating a filled block character.

Use Cases:

  • Visualization of anchor text length for identifying images with low anchor text length
  • Being a nerd
function visualizeAnchorText(anchors) {
  anchors.forEach((anchor) => {
    const anchorText = anchor.textContent;
    const anchorLength = anchorText.length;
    const visualRepresentation = '🟦'.repeat(anchorLength); // Use a filled block character (you can change this)
    
    console.log(`Anchor Text: ${anchorText}`);
    console.log(`Visual Representation: ${visualRepresentation}`);
    console.log('--------------------------'); // Separator between anchor visualizations
  });
}

// Example: Select all anchor (<a>) elements on the page
const anchorElements = document.querySelectorAll('a');

// Create and display visualizations for anchor text
visualizeAnchorText(anchorElements);

Output:

Function: This snippet is even less for the faint of heart, but nonetheless you’ve gotten this far. The goal of this snippet to divides the entire height of a document into multiple segments as defined by the function visualizeLinkDensity().

Through examining all anchor tags on the webpage, the function determines the count of links present in each segment (top of page, middle, bottom, etc) thereby effectively calculating link density. As a result, it forms a clearer picture of how links are spread across the web page.

As an example, if you invoke visualizeLinkDensity(5), it will divide the webpage into five segments and display the link density for each segment.

Use Cases:

  • Understanding link distribution of a webpage through quick visualization.
  • Auditing distribution of links across main navigation and footer
  • Being a nerd
function visualizeLinkDensity(numSegments) {
  const pageHeight = document.documentElement.scrollHeight;
  const segmentHeight = Math.ceil(pageHeight / numSegments);

  const linkCounts = new Array(numSegments).fill(0);

  const links = document.querySelectorAll('a');
  links.forEach((link) => {
    const linkRect = link.getBoundingClientRect();
    const linkTop = linkRect.top;

    // Determine which segment the link belongs to
    const segmentIndex = Math.floor(linkTop / segmentHeight);

    // Increment the link count for that segment
    linkCounts[segmentIndex]++;
  });

  // Display link density visualization in the console
  console.log('Link Density Visualization:');
  linkCounts.forEach((count, segmentIndex) => {
    const segmentRange = `${segmentIndex * segmentHeight}px - ${(segmentIndex + 1) * segmentHeight}px`;
    const densityBar = '🟦'.repeat(count); // Use a filled block character to represent link density
    console.log(`${segmentRange}: ${densityBar} (${count} links)`);
  });
}

// Example: Visualize link density by dividing the page into 5 segments
visualizeLinkDensity(5);

Output:


Posted

in

by

Tags:

Discover more from Tyler Gargula

Subscribe now to keep reading and get access to the full archive.

Continue reading