How can Angular JS detect the names of the CSS files being used in an HTML page?

I am in the process of developing a brand new widget where we are incorporating a unique feature that displays the number of CSS files included within an HTML page.

Our team requires the count and names of all CSS files utilized on the webpage.

While I am still learning Angular, I have been informed that this task can be accomplished through directives, although I am unsure of the specific steps to take.

Your assistance would be greatly appreciated. Thank you in advance!

Answer №1

Have you already implemented Angular in your application? If so, the following jQuery code can help handle this task smoothly:

var stylesheets = []
$('head link[type="text/css"]').each(function(){
    stylesheets.push($(this).attr("href"));
});
console.log("List of CSS files:" + stylesheets.join());
console.log("Total number of CSS files:" + stylesheets.length);

Answer №2

Utilizing angular framework:

  .directive('cssCounter', ['$document', function($document) {

    function filterCSSLinks(link) {
      return link.type === 'text/css' || link.rel === 'stylesheet';
    }

    function updateScopeWithCssNames(scope, document) {

      var links = document[0].querySelectorAll('link');
      var linksArray = Array.prototype.slice.call(links, 0);
      var cssLinks = linksArray.filter(filterCSSLinks);
      var cssNames = cssLinks.map(function(cssLink) {
        return cssLink.href;
      });


      scope.cssFiles = cssNames;
    }

    return {
      link: updateScopeWithCssNames,
      template: '<p>Number of CSS files: {{cssFiles.length}}<ul><li ng-repeat="c in cssFiles">{{c}}</li></ul></p>'
    };
  }]);

An illustrative plunker can be accessed via the following link: http://plnkr.co/edit/TqNAOKw4biyA7akdHfa4

Answer №3

If you want to achieve this without relying on any external libraries, here is the way to go:

let allLinks = document.querySelectorAll('link');
let linksArray = Array.prototype.slice.call(allLinks, 0);
let cssStylesheets = linksArray.filter(function(link){return link.type === 'text/css';});
let cssFileNames = cssStylesheets.map(function(stylesheet){return stylesheet.href;});
let totalNumberOfCSSFiles = cssFileNames.length;
console.log("Total number of CSS files and their names:", totalNumberOfCSSFiles, cssFileNames);

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

Managing multiple Angular calls when additional submit buttons are present

I am working on a form that includes a drop-down menu, check box, and four buttons. Whenever any action is taken (such as checking/unchecking the box, selecting an option from the drop-down, or clicking a button), it should trigger a service call to update ...

Menu button is expanded without the need to click

The Bootstrap 5 button extends the default behavior and does not collapse. Here is the code: <nav id="header-nav" class="navbar navbar-expand-lg navbar-light"> <div class="container"> <a class= ...

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

Tips to successfully utilize addEventListener on a submit action

Having issues getting this to work on submit, it functions properly when using document.getElementById("gets").addEventListener("click", b_button); but does not work when I try document.getElementById("gets").addEventListener ...

The plugin function cannot be executed unless inside the document.ready event

Utilizing jquery and JSF to construct the pages of my application includes binding functions after every ajax request, such as masks and form messages. However, I am encountering an issue where I cannot access the plugins outside of $(function(). (functio ...

The SSR React application rendering process and asynchronous code execution

When using SSR with React, how is the content that will be sent to the client constructed? Is there a waiting period for async actions to finish? Does it wait for the state of all components in the tree to stabilize in some way? Will it pause for async ...

Difficulty encountered when attempting to extract a username with multiple spaces using the .split() method in Discord.js with NodeJS

Currently, I am enhancing a feature in my Discord Bot that fetches the League of Legends statistics of a player by using the command !lolid [enter_username_here] in a Discord chat room. The function works smoothly for usernames with just one word; however, ...

Mastering the art of implementing ng-if effectively within an ng-repeat that incorporates an orderBy filter and considering the updated scope

My chat message display arranges messages from oldest to newest, with the most recent ones at the bottom. I'm using an ng-repeat on a $scope.messages array, where new chat messages are added dynamically. The orderBy filter is used to sort the messages ...

Why doesn't Mongoose automatically generate an _id for my array elements when I push them in?

I am looking for a way to have mongoose automatically add an _id field to the objects I push into my array. Here is my mongoose schema: var playerModel = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "Users", }, cl ...

Generate a dynamic vertical line that glides smoothly over the webpage, gradually shifting from one end to the other within a set duration using javascript

I have designed a calendar timeline using html. My goal is to implement a vertical line that moves from left to right as time progresses, overlaying all other html elements. This functionality is similar to Google Calendar's way of indicating the curr ...

Exploring NextJS with Typescript to utilize the getStaticProps method

I'm currently enrolled in a NextJS course and I am interested in using Typescript. While browsing through a GitHub discussion forum, I came across an issue that I don't quite understand. The first function provided below seems to be throwing an e ...

Leveraging ASP.NET MVC 5 to integrate an online document viewer from Office 365, seamlessly displaying Word documents within a sleek, compact window

We have been struggling to showcase a Word document (.docx) within an iframe on our website using the Office 365 service. The document is stored in One-Drive for business online and has been appropriately shared. After signing in, we obtained a link to the ...

Enable my textbox to interpret the html img tag

Is there a way to display emoji images instead of emoji symbols when inserting them into my textbox? For example, can I show the image representation of ':)' instead of just the symbol itself? ...

Bootstrap tab toggle feature

I'm currently facing an issue with Bootstrap's tab component. I need help figuring out how to hide a lorem ipsum section and show a hidden div when a specific tab is clicked, and then revert the changes when a different tab is selected. $(func ...

What are the mechanics behind the functionality of ES6 class instance variables?

I'm encountering an issue with the following code that is not behaving as expected: import React, { Component } from 'react'; let result = null; class MyData extends Component { _getData = () => { fetch(url) .then(response = ...

The glitch in jQuery's animate function callback

In my code to animate the sliding out of a div, I encountered an issue: var current = $('.s_text:visible'); current.animate({ right: 1014, opacity:0, },{queue: false, duration:2000}, function() { current.hide(); }); Strangely, the callbac ...

Is it better to have a single object with all required modules in NodeJS, or follow the "standard" paths in the code?

Being a fan of creating global namespaces in javascript, I often use this approach in my app development. For instance, if my application is named Xyz, I typically create an object called XYZ to organize properties and nested objects like so: XYZ.Resource ...

Leveraging the Power of CSS in Your Express Applications

Struggling to make my CSS links functional while working on localhost. Currently, when I view Index.html on my server, it displays as plain text without any styling. Even after trying the express middleware, the CSS files are still not being served, result ...

Is it possible for the HTML data attribute to store a direct link to a specific DOM element?

Can the HTML data- attributes be used to store a reference to another DOM element? As shown in this jQuery example: var domel1 = document.getElementById("#mydiv"); var domel2 = document.getElementById("#mydiv2"); $(domEl1).attr('data-domel', dom ...

Error message in Node.js with Multer: The function '.array' is not recognized

I've spent the last two days searching for a solution to this issue, but the only reference I could find was an unresolved problem reported on version 1.1.0: https://github.com/expressjs/multer/issues/338 I am using the Node.js SDK and Express framew ...