Skip to main content

script/css/
stylesheet_loader.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![cfg_attr(crown, expect(crown::jscontext_first_arg))]
6
7use std::io::{Read, Seek, Write};
8use std::sync::atomic::{AtomicUsize, Ordering};
9
10use bytes::{Bytes, BytesMut};
11use cssparser::SourceLocation;
12use encoding_rs::UTF_8;
13use js::context::JSContext;
14use net_traits::mime_classifier::MimeClassifier;
15use net_traits::request::{CorsSettings, Destination, RequestId};
16use net_traits::{
17    FetchMetadata, LoadContext, Metadata, NetworkError, ReferrerPolicy, ResourceFetchTiming,
18};
19use pixels::CorsStatus;
20use servo_arc::Arc;
21use servo_config::pref;
22use servo_url::ServoUrl;
23use style::context::QuirksMode;
24use style::global_style_data::STYLE_THREAD_POOL;
25use style::media_queries::MediaList;
26use style::shared_lock::{Locked, SharedRwLock};
27use style::stylesheets::import_rule::{ImportLayer, ImportSheet, ImportSupportsCondition};
28use style::stylesheets::{
29    ImportRule, Origin, Stylesheet, StylesheetLoader as StyleStylesheetLoader, UrlExtraData,
30};
31use style::values::CssUrl;
32
33use crate::dom::bindings::inheritance::Castable;
34use crate::dom::bindings::refcounted::Trusted;
35use crate::dom::bindings::reflector::DomGlobal;
36use crate::dom::csp::{GlobalCspReporting, Violation};
37use crate::dom::document::Document;
38use crate::dom::element::Element;
39use crate::dom::eventtarget::EventTarget;
40use crate::dom::globalscope::GlobalScope;
41use crate::dom::html::htmlelement::HTMLElement;
42use crate::dom::html::htmllinkelement::{HTMLLinkElement, RequestGenerationId};
43use crate::dom::node::NodeTraits;
44use crate::dom::performance::performanceresourcetiming::InitiatorType;
45use crate::dom::shadowroot::shadowroot::ShadowRoot;
46use crate::dom::window::CSSErrorReporter;
47use crate::event_loop::document_loader::LoadType;
48use crate::fetch::fetch::{RequestWithGlobalScope, create_a_potential_cors_request};
49use crate::fetch::network_listener::{self, FetchResponseListener, ResourceTimingListener};
50use crate::tasks::task_source::SendableTaskSource;
51use crate::unminify::{
52    BeautifyFileType, create_output_file, create_temp_files, execute_js_beautify,
53};
54
55/// An struct which is used to uniquely identify a [`StylesheetContext`] for
56/// tracking the set of script-blocking stylesheets.
57#[derive(Clone, Copy, Eq, Hash, JSTraceable, MallocSizeOf, PartialEq)]
58pub(crate) struct StylesheetContextId(usize);
59
60impl StylesheetContextId {
61    fn next() -> Self {
62        static NEXT_STYLESHEET_CONTEXT_INDEX: AtomicUsize = AtomicUsize::new(0);
63        Self(NEXT_STYLESHEET_CONTEXT_INDEX.fetch_add(1, Ordering::Relaxed))
64    }
65}
66
67pub(crate) trait StylesheetOwner {
68    /// Returns whether this element was inserted by the parser (i.e., it should
69    /// trigger a document-load-blocking load).
70    fn parser_inserted(&self) -> bool;
71
72    /// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
73    fn potentially_render_blocking(&self) -> bool;
74
75    /// Which referrer policy should loads triggered by this owner follow
76    fn referrer_policy(&self, cx: &mut JSContext) -> ReferrerPolicy;
77
78    /// Notes that a new load is pending to finish.
79    fn increment_pending_loads_count(&self);
80
81    /// Returns None if there are still pending loads, or whether any load has
82    /// failed since the loads started.
83    fn load_finished(&self, successful: bool) -> Option<bool>;
84
85    /// Sets origin_clean flag.
86    fn set_origin_clean(&self, cx: &mut JSContext, origin_clean: bool);
87}
88
89pub(crate) enum StylesheetContextSource {
90    LinkElement,
91    Import(Arc<Locked<ImportRule>>),
92}
93
94/// The context required for asynchronously loading an external stylesheet.
95struct StylesheetContext {
96    /// The id associated with this [`StylesheetContext`]. This is used to uniquely identify
97    /// it in the `Document`'s script-blocking stylesheet set.
98    id: StylesheetContextId,
99    /// The element that initiated the request.
100    element: Trusted<HTMLElement>,
101    source: StylesheetContextSource,
102    media: Arc<Locked<MediaList>>,
103    url: ServoUrl,
104    metadata: Option<Metadata>,
105    /// The response body received to date.
106    data: BytesMut,
107    /// The node document for elem when the load was initiated.
108    document: Trusted<Document>,
109    shadow_root: Option<Trusted<ShadowRoot>>,
110    origin_clean: bool,
111    /// A token which must match the generation id of the `HTMLLinkElement` for it to load the stylesheet.
112    /// This is ignored for `HTMLStyleElement` and imports.
113    request_generation_id: Option<RequestGenerationId>,
114    /// <https://html.spec.whatwg.org/multipage/#contributes-a-script-blocking-style-sheet>
115    is_script_blocking: bool,
116    /// <https://html.spec.whatwg.org/multipage/#render-blocking>
117    is_render_blocking: bool,
118}
119
120impl StylesheetContext {
121    fn unminify_css(&mut self, document: &Document, file_url: ServoUrl) {
122        let Some(unminified_dir) = document.window().unminified_css_dir() else {
123            return;
124        };
125
126        let mut style_content = std::mem::take(&mut self.data).to_vec();
127        if let Some((input, mut output)) = create_temp_files() &&
128            execute_js_beautify(
129                input.path(),
130                output.try_clone().unwrap(),
131                BeautifyFileType::Css,
132            )
133        {
134            output.seek(std::io::SeekFrom::Start(0)).unwrap();
135            output.read_to_end(&mut style_content).unwrap();
136        }
137        match create_output_file(unminified_dir, &file_url, None) {
138            Ok(mut file) => {
139                file.write_all(&style_content).unwrap();
140            },
141            Err(why) => {
142                log::warn!("Could not store script {:?}", why);
143            },
144        }
145
146        self.data = Bytes::copy_from_slice(&style_content)
147            .try_into_mut()
148            .unwrap();
149    }
150
151    fn empty_stylesheet(&self, document: &Document) -> Arc<Stylesheet> {
152        let shared_lock = document.style_shared_author_lock().clone();
153        let quirks_mode = document.quirks_mode();
154
155        Arc::new(Stylesheet::from_bytes(
156            &[],
157            UrlExtraData(self.url.get_arc()),
158            None,
159            None,
160            Origin::Author,
161            self.media.clone(),
162            shared_lock,
163            None,
164            None,
165            quirks_mode,
166        ))
167    }
168
169    fn parse(
170        &self,
171        quirks_mode: QuirksMode,
172        shared_lock: SharedRwLock,
173        css_error_reporter: &CSSErrorReporter,
174        loader: ElementStylesheetLoader<'_>,
175    ) -> Arc<Stylesheet> {
176        let metadata = self
177            .metadata
178            .as_ref()
179            .expect("Should never call parse without metadata.");
180
181        let _span = profile_traits::trace_span!("ParseStylesheet").entered();
182        Arc::new(Stylesheet::from_bytes(
183            &self.data,
184            UrlExtraData(metadata.final_url.get_arc()),
185            metadata.charset.as_deref(),
186            // The CSS environment encoding is the result of running the following steps: [CSSSYNTAX]
187            // If el has a charset attribute, get an encoding from that attribute's value. If that succeeds, return the resulting encoding. [ENCODING]
188            // Otherwise, return the document's character encoding. [DOM]
189            //
190            // TODO: Need to implement encoding http://dev.w3.org/csswg/css-syntax/#environment-encoding
191            Some(UTF_8),
192            Origin::Author,
193            self.media.clone(),
194            shared_lock,
195            Some(&loader),
196            Some(css_error_reporter),
197            quirks_mode,
198        ))
199    }
200
201    fn contributes_to_the_styling_processing_model(&self, element: &HTMLElement) -> bool {
202        if !element.upcast::<Element>().is_connected() {
203            return false;
204        }
205
206        // Whether or not this `StylesheetContext` is for a `<link>` element that comes
207        // from a previous generation. This prevents processing of earlier stylsheet URLs
208        // when the URL has changed.
209        //
210        // TODO(mrobinson): Shouldn't we also exit early if this is an import that was originally
211        // imported from a `<link>` element that has advanced a generation as well?
212        if !matches!(&self.source, StylesheetContextSource::LinkElement) {
213            return true;
214        }
215        let link = element.downcast::<HTMLLinkElement>().unwrap();
216        self.request_generation_id
217            .is_none_or(|generation| generation == link.get_request_generation_id())
218    }
219
220    /// <https://html.spec.whatwg.org/multipage/#contributes-a-script-blocking-style-sheet>
221    fn contributes_a_script_blocking_style_sheet(
222        &self,
223        element: &HTMLElement,
224        owner: &dyn StylesheetOwner,
225        document: &Document,
226    ) -> bool {
227        // el was created by that Document's parser.
228        owner.parser_inserted()
229        // el is either a style element or a link element that was an external resource link that
230        // contributes to the styling processing model when the el was created by the parser.
231        && element.downcast::<HTMLLinkElement>().is_none_or(|link|
232            self.contributes_to_the_styling_processing_model(element)
233            // el's style sheet was enabled when the element was created by the parser.
234            && !link.is_effectively_disabled()
235        )
236        // el's media attribute's value matches the environment.
237        && element.media_attribute_matches_media_environment()
238        // The last time the event loop reached step 1, el's root was that Document.
239        && *element.owner_document() == *document
240        // The user agent hasn't given up on loading that particular style sheet yet.
241        // A user agent may give up on loading a style sheet at any time.
242        //
243        // This might happen when we time out a resource, but that happens in `fetch` instead
244    }
245
246    fn decrement_blockers_and_finish_load(
247        self,
248        document: &Document,
249        cx: &mut js::context::JSContext,
250    ) {
251        if self.is_script_blocking {
252            document.remove_script_blocking_stylesheet(self.id);
253        }
254
255        if self.is_render_blocking {
256            document.decrement_render_blocking_element_count();
257        }
258
259        document.finish_load(LoadType::Stylesheet(self.url), cx);
260    }
261
262    fn do_post_parse_tasks(
263        self,
264        success: bool,
265        stylesheet: Arc<Stylesheet>,
266        cx: &mut js::context::JSContext,
267    ) {
268        let element = self.element.root();
269        let document = self.document.root();
270        let owner = element
271            .upcast::<Element>()
272            .as_stylesheet_owner()
273            .expect("Stylesheet not loaded by <style> or <link> element!");
274
275        match &self.source {
276            // https://html.spec.whatwg.org/multipage/#link-type-stylesheet%3Aprocess-the-linked-resource
277            StylesheetContextSource::LinkElement => {
278                let link = element
279                    .downcast::<HTMLLinkElement>()
280                    .expect("Should be HTMLinkElement due to StylesheetContextSource");
281                // For failed requests, we should bail out if it is from a previous generation.
282                // Since we can reissue another failed request, which resets the pending load counter
283                // in a link element.
284                if self
285                    .request_generation_id
286                    .is_some_and(|generation| generation != link.get_request_generation_id())
287                {
288                    self.decrement_blockers_and_finish_load(&document, cx);
289                    return;
290                }
291                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet
292                // > When the disabled attribute of a link element with a stylesheet keyword is set,
293                // > disable the associated CSS style sheet.
294                if link.is_effectively_disabled() {
295                    stylesheet.set_disabled(true);
296                }
297                // Step 3. If el has an associated CSS style sheet, remove the CSS style sheet.
298                // Step 4. If success is true, then:
299                // Step 4.1. Create a CSS style sheet with the following properties:
300                //
301                // Note that even in the failure case, we should create an empty stylesheet.
302                // That's why `set_stylesheet` also removes the previous stylesheet
303                link.set_stylesheet(cx.no_gc(), stylesheet);
304            },
305            StylesheetContextSource::Import(import_rule) => {
306                let mut guard = document.style_shared_author_lock().write();
307                import_rule.write_with(&mut guard).stylesheet = ImportSheet::Sheet(stylesheet);
308            },
309        }
310
311        if let Some(ref shadow_root) = self.shadow_root {
312            shadow_root.root().invalidate_stylesheets(cx.no_gc());
313        } else {
314            document.invalidate_stylesheets(cx.no_gc());
315        }
316        owner.set_origin_clean(cx, self.origin_clean);
317
318        // Remaining steps are a combination of
319        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet%3Aprocess-the-linked-resource
320        // and https://html.spec.whatwg.org/multipage/#the-style-element%3Acritical-subresources
321
322        // Step 4.2. Fire an event named load at el.
323        // Step 5. Otherwise, fire an event named error at el.
324        if let Some(any_failed) = owner.load_finished(success) {
325            // Only fire an event if we have no more pending events
326            // (in which case `owner.load_finished` would return None)
327            let event = match any_failed {
328                true => atom!("error"),
329                false => atom!("load"),
330            };
331            element.upcast::<EventTarget>().fire_event(cx, event);
332        }
333        // Regardless if there are other pending events, we need to unblock
334        // rendering for this particular request and signal that the load has finished
335
336        // Step 6. If el contributes a script-blocking style sheet, then:
337        // Step 7. Unblock rendering on el.
338        self.decrement_blockers_and_finish_load(&document, cx);
339    }
340}
341
342impl FetchResponseListener for StylesheetContext {
343    fn process_request_body(&mut self, _: &GlobalScope, _: RequestId) {}
344
345    fn process_response(
346        &mut self,
347        _: &mut js::context::JSContext,
348        _: &GlobalScope,
349        _: RequestId,
350        metadata: Result<FetchMetadata, NetworkError>,
351    ) {
352        if let Ok(metadata) = metadata.as_ref() &&
353            metadata.cors_status() == CorsStatus::Unsafe
354        {
355            self.origin_clean = false;
356        }
357
358        self.metadata = metadata.ok().map(Into::into);
359    }
360
361    fn process_response_chunk(
362        &mut self,
363        _: &mut js::context::JSContext,
364        _: &GlobalScope,
365        _: RequestId,
366        payload: Bytes,
367    ) {
368        self.data.extend_from_slice(&payload);
369    }
370
371    fn process_response_eof(
372        mut self,
373        cx: &mut js::context::JSContext,
374        global: &GlobalScope,
375        _: RequestId,
376        status: Result<(), NetworkError>,
377        timing: ResourceFetchTiming,
378    ) {
379        network_listener::submit_timing(cx, global, &self, &status, &timing);
380
381        let document = self.document.root();
382        let Some(metadata) = self.metadata.as_ref() else {
383            let empty_stylesheet = self.empty_stylesheet(&document);
384            self.do_post_parse_tasks(false, empty_stylesheet, cx);
385            return;
386        };
387
388        let element = self.element.root();
389
390        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:process-the-linked-resource
391        if element.is::<HTMLLinkElement>() {
392            // Step 1. If the resource's Content-Type metadata is not text/css, then set success to false.
393            let is_css = MimeClassifier::is_css(
394                &metadata.resource_content_type_metadata(LoadContext::Style, &self.data),
395            ) || (
396                // From <https://html.spec.whatwg.org/multipage/#link-type-stylesheet>:
397                // > Quirk: If the document has been set to quirks mode, has the same origin as
398                // > the URL of the external resource, and the Content-Type metadata of the
399                // > external resource is not a supported style sheet type, the user agent must
400                // > instead assume it to be text/css.
401                document.quirks_mode() == QuirksMode::Quirks &&
402                    document.origin().immutable().clone() == metadata.final_url.origin()
403            );
404
405            if !is_css {
406                let empty_stylesheet = self.empty_stylesheet(&document);
407                self.do_post_parse_tasks(false, empty_stylesheet, cx);
408                return;
409            }
410
411            // Step 2. If el no longer creates an external resource link that contributes to the styling processing model,
412            // or if, since the resource in question was fetched, it has become appropriate to fetch it again, then:
413            if !self.contributes_to_the_styling_processing_model(&element) {
414                // Step 2.1. Remove el from el's node document's script-blocking style sheet set.
415                self.decrement_blockers_and_finish_load(&document, cx);
416                // Step 2.2. Return.
417                return;
418            }
419        }
420
421        if metadata.status != http::StatusCode::OK {
422            let empty_stylesheet = self.empty_stylesheet(&document);
423            self.do_post_parse_tasks(false, empty_stylesheet, cx);
424            return;
425        }
426
427        self.unminify_css(&document, metadata.final_url.clone());
428
429        let loader = if pref!(dom_parallel_css_parsing_enabled) {
430            ElementStylesheetLoader::Asynchronous(AsynchronousStylesheetLoader::new(&element))
431        } else {
432            ElementStylesheetLoader::Synchronous { element: &element }
433        };
434        loader.parse(self, &element, &document, cx);
435    }
436
437    fn process_csp_violations(
438        &mut self,
439        cx: &mut js::context::JSContext,
440        global: &GlobalScope,
441        _request_id: RequestId,
442        violations: Vec<Violation>,
443    ) {
444        global.report_csp_violations(cx, violations, None, None);
445    }
446
447    fn process_content_length(&mut self, _request_id: RequestId, size: usize) {
448        self.data.reserve(size.saturating_sub(self.data.len()));
449    }
450}
451
452impl ResourceTimingListener for StylesheetContext {
453    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
454        let initiator_type =
455            InitiatorType::LocalName(self.element.root().upcast::<Element>().local_name().clone());
456        (initiator_type, self.url.clone())
457    }
458}
459
460pub(crate) enum ElementStylesheetLoader<'a> {
461    Synchronous { element: &'a HTMLElement },
462    Asynchronous(AsynchronousStylesheetLoader),
463}
464
465impl<'a> ElementStylesheetLoader<'a> {
466    pub(crate) fn new(element: &'a HTMLElement) -> Self {
467        ElementStylesheetLoader::Synchronous { element }
468    }
469}
470
471impl ElementStylesheetLoader<'_> {
472    pub(crate) fn load_with_element(
473        cx: &mut JSContext,
474        element: &HTMLElement,
475        source: StylesheetContextSource,
476        media: Arc<Locked<MediaList>>,
477        url: ServoUrl,
478        cors_setting: Option<CorsSettings>,
479        integrity_metadata: String,
480    ) {
481        let document = element.owner_document();
482        let shadow_root = element
483            .containing_shadow_root()
484            .map(|shadow_root| Trusted::new(&*shadow_root));
485        let generation = element
486            .downcast::<HTMLLinkElement>()
487            .map(HTMLLinkElement::get_request_generation_id);
488        let mut context = StylesheetContext {
489            id: StylesheetContextId::next(),
490            element: Trusted::new(element),
491            source,
492            media,
493            url: url.clone(),
494            metadata: None,
495            data: BytesMut::new(),
496            document: Trusted::new(&*document),
497            shadow_root,
498            origin_clean: true,
499            request_generation_id: generation,
500            is_script_blocking: false,
501            is_render_blocking: false,
502        };
503
504        let owner = element
505            .upcast::<Element>()
506            .as_stylesheet_owner()
507            .expect("Stylesheet not loaded by <style> or <link> element!");
508        let referrer_policy = owner.referrer_policy(cx);
509        owner.increment_pending_loads_count();
510
511        // Final steps of https://html.spec.whatwg.org/multipage/#update-a-style-block
512        // and part of https://html.spec.whatwg.org/multipage/#link-type-stylesheet:linked-resource-fetch-setup-steps
513
514        // If element contributes a script-blocking style sheet, append element to its node document's script-blocking style sheet set.
515        context.is_script_blocking =
516            context.contributes_a_script_blocking_style_sheet(element, owner, &document);
517        if context.is_script_blocking {
518            document.add_script_blocking_stylesheet(context.id);
519        }
520
521        // If element's media attribute's value matches the environment and
522        // element is potentially render-blocking, then block rendering on element.
523        context.is_render_blocking = element.media_attribute_matches_media_environment() &&
524            owner.potentially_render_blocking() &&
525            document.allows_adding_render_blocking_elements();
526        if context.is_render_blocking {
527            document.increment_render_blocking_element_count();
528        }
529
530        // https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource
531        let global = element.global();
532        let request = create_a_potential_cors_request(
533            Some(document.webview_id()),
534            url.clone(),
535            Destination::Style,
536            cors_setting,
537            None,
538            global.get_referrer(),
539        )
540        .with_global_scope(&global)
541        .referrer_policy(referrer_policy)
542        .integrity_metadata(integrity_metadata);
543
544        document.fetch_blocking(LoadType::Stylesheet(url), request, context);
545    }
546
547    fn parse(
548        self,
549        listener: StylesheetContext,
550        element: &HTMLElement,
551        document: &Document,
552        cx: &mut js::context::JSContext,
553    ) {
554        let shared_lock = document.style_shared_author_lock().clone();
555        let quirks_mode = document.quirks_mode();
556        let window = element.owner_window();
557
558        match self {
559            ElementStylesheetLoader::Synchronous { .. } => {
560                let stylesheet =
561                    listener.parse(quirks_mode, shared_lock, window.css_error_reporter(), self);
562                listener.do_post_parse_tasks(true, stylesheet, cx);
563            },
564            ElementStylesheetLoader::Asynchronous(asynchronous_loader) => {
565                let css_error_reporter = window.css_error_reporter().clone();
566                let task_source = window
567                    .as_global_scope()
568                    .task_manager()
569                    .networking_task_source()
570                    .to_sendable();
571
572                let parse_stylesheet = move || {
573                    let loader = ElementStylesheetLoader::Asynchronous(asynchronous_loader);
574                    let stylesheet =
575                        listener.parse(quirks_mode, shared_lock, &css_error_reporter, loader);
576
577                    task_source.queue(
578                        task!(finish_parsing_of_stylesheet_on_main_thread: move |cx| {
579                            listener.do_post_parse_tasks(true, stylesheet, cx);
580                        }),
581                    );
582                };
583
584                let thread_pool = STYLE_THREAD_POOL.pool();
585                if let Some(thread_pool) = thread_pool.as_ref() {
586                    thread_pool.spawn(parse_stylesheet);
587                } else {
588                    parse_stylesheet();
589                }
590            },
591        };
592    }
593}
594
595impl StyleStylesheetLoader for ElementStylesheetLoader<'_> {
596    /// Request a stylesheet after parsing a given `@import` rule, and return
597    /// the constructed `@import` rule.
598    fn request_stylesheet(
599        &self,
600        url: CssUrl,
601        source_location: SourceLocation,
602        lock: &SharedRwLock,
603        media: Arc<Locked<MediaList>>,
604        supports: Option<ImportSupportsCondition>,
605        layer: ImportLayer,
606    ) -> Arc<Locked<ImportRule>> {
607        // Ensure the supports conditions for this @import are true, if not, refuse to load
608        if supports.as_ref().is_some_and(|s| !s.enabled) {
609            return Arc::new(lock.wrap(ImportRule {
610                url,
611                stylesheet: ImportSheet::new_refused(),
612                supports,
613                layer,
614                source_location,
615            }));
616        }
617
618        let resolved_url = match url.url().cloned() {
619            Some(url) => url,
620            None => {
621                return Arc::new(lock.wrap(ImportRule {
622                    url,
623                    stylesheet: ImportSheet::new_refused(),
624                    supports,
625                    layer,
626                    source_location,
627                }));
628            },
629        };
630
631        let import_rule = Arc::new(lock.wrap(ImportRule {
632            url,
633            stylesheet: ImportSheet::new_pending(),
634            supports,
635            layer,
636            source_location,
637        }));
638
639        // TODO (mrnayak) : Whether we should use the original loader's CORS
640        // setting? Fix this when spec has more details.
641        let source = StylesheetContextSource::Import(import_rule.clone());
642
643        match self {
644            ElementStylesheetLoader::Synchronous { element } => {
645                // TODO: https://github.com/servo/servo/issues/44685
646                #[expect(unsafe_code)]
647                let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
648                Self::load_with_element(
649                    &mut cx,
650                    element,
651                    source,
652                    media,
653                    resolved_url.into(),
654                    None,
655                    String::new(),
656                );
657            },
658            ElementStylesheetLoader::Asynchronous(AsynchronousStylesheetLoader {
659                element,
660                task_source,
661            }) => {
662                let element = element.clone();
663                task_source.queue(task!(load_import_stylesheet_on_main_thread: move |cx| {
664                    Self::load_with_element(
665                        cx,
666                        &element.root(),
667                        source,
668                        media,
669                        resolved_url.into(),
670                        None,
671                        String::new(),
672                    );
673                }));
674            },
675        }
676
677        import_rule
678    }
679}
680
681pub(crate) struct AsynchronousStylesheetLoader {
682    element: Trusted<HTMLElement>,
683    task_source: SendableTaskSource,
684}
685
686impl AsynchronousStylesheetLoader {
687    pub(crate) fn new(element: &HTMLElement) -> Self {
688        let window = element.owner_window();
689        Self {
690            element: Trusted::new(element),
691            task_source: window
692                .as_global_scope()
693                .task_manager()
694                .networking_task_source()
695                .into(),
696        }
697    }
698}