Save the script source in an array

When it comes to loading assets such as js & css from the next page and storing them in an Array, I have implemented a method where I iterate through the document and store the JavaScript links separately. It currently looks like this:

0:{images: Array(61)}
1:{js: script}
2:{js: script}
3:{js: script}
4:{js: script}
5:{js: script}
6:{js: script}
etc...

Below is the loop in question:

[].forEach.call( document.querySelectorAll("script[src]"), function( src ) {
    console.log( src );
    resources.push({js: src})
 });

My query is, how can I store these JavaScript links in one object like the images, instead of pushing them separately?

Answer №1

Initially, you insert {js: []} into the resources array once, and then proceed to insert the scripts into the array that is assigned as the value of the js property.

(However, it may not be the most logical approach to handle it this way, as it could be more efficient to have resources structured as an object with separate images and js properties instead of just an array).

Answer №2

If you want to grab resources, you have a few options:

resources.push( {js : [ ...document.querySelectorAll( "script[src]" ) ] } );

Alternatively, you could improve efficiency by setting them as properties of the resource object:

resource = {};
resources.js = [ ...document.querySelectorAll( "script[src]" ) ];
resources.images = [ ...document.querySelectorAll( "img" ) ];

To cater to older browsers, you can use the following:

var toArray = function( arrLike ){ return [].slice.call( arrLike ) };
resource = {};
resources.js = toArray( document.querySelectorAll( "script[src]" ) );
resources.images = toArray( document.querySelectorAll( "img" ) );

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

Uncertain about the ins and outs of AJAX

I am a complete beginner in web development. Although I have studied JavaScript and HTML through books, my understanding is still limited. I have never worked with AJAX before and find most online examples too complex for me to follow. My goal is to crea ...

Indicator count for multiple slick carousels

Is there a way to create individual slide counters for multiple sliders that do not work together? In my current example, the slide counters are functioning together: https://codepen.io/anon/pen/oqqYjB?editors=1010 <div class="container"> <div ...

What is the best way to manage the "checked" state of an input checkbox using React?

I'm currently developing an application that features a form with radio buttons. One of the radio button options can be toggled on/off using a checkbox, but I want to ensure that the checkbox is disabled if the corresponding radio button is not selec ...

Rails : CSS/JavaScript functioning perfectly on local server, facing issues on Heroku deployment

My Rails website features various CSS animation effects and JavaScript elements. While these transitions function smoothly on my local environment, they do not work properly on Heroku. Examining the Heroku logs: 2013-09-17T17:13:36.081145+00:00 app[web.1 ...

Change the input field to uppercase using JavaScript but do not use inline JavaScript

Hey there! I have a basic script set up (see below) with an input field allowing users to enter a query. This query is then sent to a socrata webservice to request specific data, which is displayed in an alert box. So far, everything works smoothly. var l ...

Creating a duplicate object in a React component

I am currently developing a basic react application with inputs such as first name, last name, etc... The input states are managed using context api in the following context.js: import React, { useState } from "react"; export const FormContext ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

Tips for organizing data and dynamically linking options to another select value?

One of my challenges involves working with two select elements. The first select allows for multiple options, while the second select is dependent on the choice made in the first one. <select class="form-control" id="select1"> <option value=""& ...

Tips for deactivating all JavaScript events on a webpage that has been loaded within an iframe

My website is equipped with various JS click/mouseover/mouseout/scroll events and incorporates several JS libraries to operate features such as carousels, bootstrap modal pop-ups, and more. I am looking to halt all events on a specific element. Although I ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

Enhanced coding experience with JavaScript completion and ArangoDB module management

Exploring New Horizons After more than a decade of using Eclipse for Java development, I have decided to delve into the realms of javascript and arangodb due to high demand. My current task involves developing multiple microservices to run within arangodb ...

PostMan gives me an error when I attempt to send an image file to NodeJS using multer (req.file is undefined)

After encountering issues with saving image files to the server using multer-s3, I attempted to use multer and s3Client instead. Unfortunately, I faced similar challenges as req.file or req.files from the multer-s3 middleware continued to return undefined. ...

What are the best ways to incorporate mistakes into my JavaScript mortgage calculator?

I am struggling to set up my calculator so that it triggers an error message if the APR goes over 25% or falls below 0. Also, the Loan Term should be greater than 0 and less than or equal to 40, otherwise display an error message. I have attempted differen ...

The issue with Firefox's DOMContentLoaded event

After creating a script that interacts with the Dom, I noticed that it needs to wait until the Dom is ready before executing each operation. My intention is to make this script usable in two ways: Include it in the head tag, ensuring it loads before the ...

Discovering child elements within an iframe using Angular and customizing their appearance

Is there a simple and effective way to locate child nodes within an iframe using Angular in order to access the HTML element? Currently, I have implemented the following method: I designated a reference variable within my iframe (#privacyPolicy) <ifra ...

What is the alternative method in JavaScript for locating items instead of using indexOf?

I have a set of paths in an array. Some paths are classified as constants while others are labeled as dynamic. A constant path would be something like "/booking-success", whereas a dynamic path could be something like '/arrival/view/:job_or ...

Performing two rounds of filtering on a NumPy array and then

Is there a more efficient way to execute two filtering steps and one replacing step on a large array without the need for making copies or using loops? For example, consider two numpy arrays of different sizes. I want to apply two filters. The first filte ...

An issue occurred during rendering: `TypeError: Unable to retrieve the length property of an undefined value`

I want to display an overlay only when there is text in my search input. Below is the template for my input field: Input.vue: <template> <div> <input v-model="query" class="input" placeholder="Global search..."></input&g ...

Is there a way to confirm if all div elements have a designated background color?

I have a scenario where I have dynamically added several divs with a specific class to my webpage. These divs change color when the user hovers over them. I am trying to trigger a specific function once the last div has been set to a particular backgroun ...

Tips for accessing JSON values in JavaScript

How can I extract values from a JSON object in JavaScript? Below is the code snippet I've tried: var obj={"0.5":0.009333, "0.21":0.048667,"0.31":0.070667}; var value =0.21; var p=0; for(i=0; i<= obj.length ;i++){ if(value== obj[i]) ...