Is it possible to determine if <script> elements were included in the HTML source code or loaded in using another JavaScript script?

For instance, when I use the code below to retrieve a NodeList of all scripts on a webpage:

document.querySelectorAll('script')

Is there a method to distinguish between scripts that were part of the original HTML source and those that were added later via other scripts?

I attempted to compare the data in the properties of each node/script:

However, I have yet to identify any distinct characteristics that set apart scripts present in the HTML source from ones loaded through another script.

While I recognize that I can obtain this information using the Network tab in developer tools under the initiator column, I am interested in being able to differentiate scripts programmatically with JavaScript if feasible.

If an alternative method to

document.querySelectorAll('script')
is necessary, I am open to exploring it as well.

Thank you for your help!

Answer №1

Request

If you're looking to identify all script tags that are dynamically added to the DOM post page load.

These could be either external scripts (connecting to a .js file) or inline-scripts, which were not part of the original HTML content.

Solution

To achieve this, you can intercept the document.createElement function and assign a unique data-external attribute to any script tags created after the initial page load.

You can then filter these tagged scripts to specifically target the external ones.

Presumptions

  • Make sure the hook code provided below is executed before anything else.
  • Have authority over the original HTML document
  • All external script additions are made through document.createElement method (although other atypical methods are disregarded in this solution)

Intercepting document.createElement

// Redefine the 'createElement' function
document.createElement = function(originalCreateFunc) {
    // return a customized new function, acting as our interception function.
    return function() {
        // invoke the original function to create the element
        var element = originalCreateFunc.apply(this, arguments);
        // verify if the created element is of 'script' type
        if (element.tagName.toLowerCase() === "script") {
            // if it's a script tag, add an attribute
            element.setAttribute("data-external", "true");
        }
        // return the modified element
        return element;
    };
}(document.createElement);

Filtering External Scripts

To exclusively fetch the external scripts, use the following line of code.

// Select only script tags with the 'data-external' attribute set to 'true'
document.querySelectorAll('script[data-external="true"]');

Answer №2

If you have full control over the HTML and JavaScript, you have the ability to add elements directly to the original HTML without affecting dynamically loaded content. For example, all HTML scripts could be structured like this:

<script class="html" src="..."></script>

When iterating through the scripts, you can check for this specific class:

document.querySelectorAll('script').forEach(s => {
    if (s.classList.contains("html")) {
        // do something
    } else { 
        // do something different
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Quickest Way to Retrieve Attribute Values in JavaScript

I'm trying to access a specific attribute called "data-price". Any tips on how I can retrieve the value of this attribute using this syntax: Preferred Syntax div[0].id: 48ms // appears to be the quickest method Alternative Syntax - Less Efficient ...

Using jQuery to eliminate selected item from a list

I have a basic list in html/jquery that allows users to add items. I am trying to create functionality where a specific item can be removed from the list when clicked on. However, the code for removing the item is not working as expected. Remove Item Code ...

Comparison of Performance: PHP-Rendered Content vs. Using JavaScript and DOM with AJAX

Let's discuss a simple task: retrieving a list of products from a database and displaying it on a webpage. There are 2 different setups to consider: Setup1: Using a PHP script for querying. All the content is generated server-side, with the complete ...

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

Find the hex code corresponding to the darkest color in the JSON response

I'm working with a json response that contains various vehicle objects, each with a hexcode value representing the color of the vehicle: [ { "name":"Ford", "hexCode": "4B1A1F"}, { "name":"BMW", "hexCode": "FFFFFF"}, { "name":"Fiat", "hexCode" ...

Angular directive ng-if on a certain path

Is it possible to display a specific div based on the route being viewed? I have a universal header and footer, but I want to hide something in the header when on the / route. <body> <header> <section ng-if=""></section&g ...

Using React to dynamically change the page based on button clicks

Currently, I am facing a challenge with my react application development. This is my first time working on a react project and I am encountering some issues. In one of the functional components, I am calling and displaying another functional component twic ...

Merge rxjs streams, identify modifications, and yield a single result

In the context of using Angular with .net Core WebApi, let's consider the development of a time management application designed to monitor task durations. The user initiates a task on the front end which triggers a timer displaying elapsed time. The ...

The Node child process remains active indefinitely, persisting even after receiving the necessary data

Currently, I am tackling a loopback project that involves running a background job using Node child processes. As a beginner, I find the documentation somewhat perplexing. If anyone can provide guidance or suggestions, it would be highly appreciated. The l ...

Encountering issues while retrieving information from database through AJAX and PHP

Update: The initial section of this question has been resolved and is now updated with the working code. ~ I'm currently developing a JavaScript application, and I'm encountering challenges with making an AJAX call function properly. While I ha ...

Distinguishing Jquery and Ajax

Could someone kindly provide a comparison of the distinctions between Jquery and Ajax? ...

"Enhance Your Online Shopping Experience with Woocommerce Ajax Filters and

I have a structure that looks like this: Company Google Apple Microsoft Material Wood Metal Plastic Essentially, Brand & Material are attributes in the Woocommerce system, while the rest are variables. I am currently working on implementing AJAX fi ...

Multiple AJAX Requests in JavaScript Are Providing Incorrect Data Simultaneously

My current challenge involves populating an array with strings from two separate ajax calls. These strings are then used to create div elements with IDs matching the string names, each containing data retrieved from twitch streamers via the ajax requests. ...

The program encountered an error while trying to access the 'username' property, as it was undefined

I've been working on implementing user associations for the /campgrounds section, but encountered this error unexpectedly Cannot read property 'username' of undefined at eval (C:\Users\karan\Desktop\YelpCamp\V9&b ...

Applying various Angular filters to an array of objects within HTML select elements

I'm fairly new to working with JS and the rather challenging learning curve of AngularJS. I have an array containing numerous objects with the relevant properties listed below: $scope.myRecs = [{country: 'Ireland', city: 'Dublin&apos ...

Is there a way to change this coffeescript into js/jquery?

content = element.html() content = content.replace(/(#include(\s*&lt;.*&gt;)?)/gi, '<span>$1</span>') content = content.replace(/(main\(.*\))/gi, '<span>$1</span>') element.html(content) h ...

ng-if to switch elements on and off

Looking to dynamically toggle DOM elements in a dashboard using ng-if. This is how my HTML is structured: //Buttons <div> <button ng-click="showDiv('div1');"></button> <button ng-click="showDiv('div2');"></ ...

jqxChart displaying data with proportions

Exploring the waterfall series feature of the jqxChart was quite interesting. As per its API, the code snippet below is used to set the values of the y-axis: valueAxis: { title: {text: 'Population<br>'}, unitInterval: 1000000, ...

Bring back hover guidelines following mouse click

I have implemented a script to toggle the visibility of my main navigation menu items. Check out the live demo here: ! There is a specific section of my menu that includes downward arrows (displayed using font awesome icons within <i> tags), which s ...

Difficulty Navigating Table Elements Using jQuery

My goal is to hide specific elements within a table by using a jQuery function that iterates through each row, checks the row's class, and hides it based on the result. However, I've encountered an issue where the function only checks the first r ...