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