Demonstrate HTML and CSS integration through the use of the http.get method

In an attempt to create an iframe-like solution, I am using an http.get call to retrieve a site as an object containing HTML and CSS. The issue arises when using <link> tags because the CSS path is obtained from an external source, causing the HTML to load before all the CSS is applied.

Even though I thought that

link.onload = () => { sub$.next(); sub$.complete() }
would fix this problem, there are still challenges with loading them in the correct order.

Html$ = this._idToGetUrl.pipe(
    filter(id=> id!= null),
    switchMap(id => {
        return this.http.get<any>(this.baseUrl(id))
            .pipe(
                switchMap(x => this.setLinkTags(x.css)
                    .pipe(map(_ => x.html))
                ),
                catchError(this.handleError)
            );
    })
)

private setLinkTags = (css: CSS[]) => {
    const check = css.map((css, i) => {
        const sub$ = new Subject()
        if (document.querySelector(`[href="${css.path}"]`)) {
            sub$.next()
            sub$.complete()
            return sub$
        }
        const link = document.createElement('link')
        link.setAttribute("rel", "stylesheet")
        link.setAttribute("type", "text/css")
        link.onload = () => { sub$.next(); sub$.complete() }
        link.onerror = () => { sub$.next(); sub$.complete() }
        link.setAttribute("href", css.path)
        document.getElementsByTagName("head")[0].appendChild(link)
        return sub$
    })
    return zip(of(...check))
}

Answer №1

onload is not the most effective method for verifying the availability of a css file. Consider using this alternative approach:

var loadCSS = function(url, callback){
    var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = url;

    document.getElementsByTagName('head')[0].appendChild(link);

    var img = document.createElement('img');
        img.onerror = function(){
            if(callback) callback(link);
        }
        img.src = url;
}

You can substitute callback() with subject.next() and make necessary code adjustments to accommodate it.

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

Initiating a GET request to retrieve the file generated by the server

I am currently delving into the Mean stack and have encountered a challenge with downloading a file from my server-side application using the Angular front end. Despite successfully generating the file on the back end, clicking the download button on the f ...

Retrieve the attributes associated with a feature layer to display in a Pop-up Template using ArcGIS Javascript

Is there a way to retrieve all attributes (fields) from a feature layer for a PopupTemplate without explicitly listing them in the fieldInfos object when coding in Angular? .ts const template = { title: "{NAME} in {COUNTY}", cont ...

Can you please explain to me the purpose of the ncu -u command?

Struggling to update my Angular project in Visual Studio to a specific version of Angular. Instead of following the tutorial that provided me with the latest Angular version, I wanted to install version 6 specifically. So, I ran npm install -g @angular/ [ ...

Center the image and align the floated texts on each side horizontally

I've recently started learning about HTML and CSS, but I'm having trouble grasping one concept. My goal is to align two floating <p> elements on either side of a centered <img>. Here's an example of what I'm trying to achiev ...

Ways to use DecimalPipe for rounding numbers in Angular - Up or down, your choice!

Looking to round a number up or down using DecimalPipe in Angular? By default, DecimalPipe rounds a number like this: Rounding({{value | number:'1.0-2'}}) 1.234 => 1.23 1.235 => 1.24 But what if you want to specifically round up or do ...

Guide on setting the BackColor of a table cell based on a database value dynamically

In the project I am currently working on, there is a request to change the background color of specific table cells based on their values. In order to achieve this, I am handling the RadGrid_ItemDataBound event and attempting to set the BackColor property ...

The styling for buttons links is malfunctioning

I am currently developing my own version of Bootstrap and focusing on buttons and links. I have anchor tags within the button element, but the link styling is not displaying correctly. HTML <button class="btn-danger"><a href="#">Danger</a& ...

jQuery: Select the parent element of a focused form input and apply styling

Recently, I encountered a situation where I have a form containing a DIV along with 3 INPUTS, each enclosed within a LABEL element. My goal is to alter the background image of the DIV whenever an INPUT receives focus. Due to limitations in navigating up t ...

Making a floating action button in Ionic

I am currently working on creating an action floating button using the Ionic framework. While I have successfully created a basic button, I am now looking to add some stylish effects and make additional buttons appear upon interaction. I understand that th ...

How can I display JSON values without revealing the parent in Angular 5 and Ionic 3?

I am trying to extract values from JSON without the parent keys. Here is the JSON structure I have: [ { "companies": [{ "id": 1, "name": "Prueba", "company_number": "23423423A", "latitude": 241241.12, "lo ...

Tips for styling a button upon being clicked

Is there a CSS technique to make a button change color when clicked with the mouse? I am aware of using ':hover' for changing color, but I need something specific to a left mouse click. I want the same functionality as a standard button but with ...

Issues with Autofocus while Searching and Selecting from Dropdown menu

Here is the JavaScript code I am using: <script type="text/javascript"> function handleSelectionChange(selectElement, nextField) { nextField.focus(); } function handleKeyPress(event, currentField, nextField) { i ...

Issue with IE 11: Including card image inside anchor tags in Bootstrap 4 causes unwanted white space

I'm having an issue with my Bootstrap 4 card markup where the image is wrapped inside an anchor tag. The problem arises when viewing it in IE 11, as there is a large white space underneath the image, while everything displays fine in Chrome, Edge, and ...

Why do users struggle to move between items displayed within the same component in Angular 16?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB). During the implementation of a movies search feature, I encountered an unexpected issue. Within the app\servic ...

Converting a String into a Type or Component in Angular: A Step-by-Step Guide

Is it feasible in Angular to convert a string into a specific type or component? For instance, if I have the string "ListComponent", could I dynamically add a ListComponent to the application without using mapping techniques? stringComponent = "ListComp ...

Adjust the image to stretch and crop appropriately to perfectly fit the specified dimensions

I have a div with an image inside of it, and the overflow of the div is set to hidden so that the image will be cropped if it exceeds the width or height. It was working correctly, but sometimes it doesn't. What could be causing this issue? Here is th ...

Wave your way to unique text creation with Firefox

Hey there, I've got some text inside a div that's been transformed with rotate(3deg). Strangely enough, in Firefox, the text appears wavy. When I remove the transform property from the div, the waviness disappears. Is there any way for me to keep ...

Guide on using an image as a background in a <svg> element with React.js

I am facing an issue with filling an SVG path with a background image. I have tried various methods found on Google, but none seem to work as expected. Here is the code snippet I have been working with: <div className="intro"> ...

Images positioned next to each other appear distorted when adjusting for different screen sizes

I have been struggling with this issue for quite some time and I just can't seem to get it right. My goal is to display two images side by side with a gap between them. The problem arises when the browser is resized, as the gap disappears and the im ...

When you click, you will be directed to the specific details of the object

I have a recipe component that displays a list of recipes from my database and a recipe-detail component that should show the details of a selected recipe. What I aim to achieve is that when someone clicks on a recipe name, they are routed to the recipe-de ...