Start Coding with Codelab | Jaeves AI

Create Swagger Configuration in Laravel – Jaeves Codelab

Written by Admin | Oct 11, 2023 1:26:47 PM

To optimize the code and make it cover all possible scenarios, you can make several improvements:

Step 1:

Use a DOMContentLoaded event and not load event to make sure the code runs as soon as the DOM is ready, which will ensure it runs before Google bots scan the page.

Step 2:

Make the selector catch all external links that open in a new tab 

Step 3:

Optimize the conditional logic for better readability and performance.


document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll('a[target="_blank"]').forEach((link) => {
        let currentRel = link.getAttribute("rel") || "";
        let newRel = "noopener noreferrer";

        if (currentRel) {
            let relArray = currentRel.split(" ").map(item => item.trim().toLowerCase());
            if (relArray.includes("noopener")) newRel = newRel.replace("noopener", "");
            if (relArray.includes("noreferrer")) newRel = newRel.replace("noreferrer", "");
            newRel = currentRel + " " + newRel.trim();
        }

        link.setAttribute("rel", newRel.trim());
    });
});

The pervious code should effectively add rel="noopener noreferrer" to all external links that open in a new browser tab and load before Google bots scan the page.