Worklet: phương thức addModule()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2021.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Phương thức addModule() của giao diện Worklet tải mô-đun trong tệp JavaScript đã cho và thêm nó vào Worklet hiện tại.

Cú pháp

js
addModule(moduleURL)
addModule(moduleURL, options)

Tham số

moduleURL

Một String chứa URL của tệp JavaScript có mô-đun cần thêm.

options Optional

Một đối tượng với bất kỳ tùy chọn nào sau đây:

credentials

Một giá trị Request.credentials cho biết có gửi thông tin xác thực (ví dụ: cookie và xác thực HTTP) khi tải mô-đun hay không. Có thể là "omit", "same-origin", hoặc "include". Mặc định là "same-origin". Xem thêm Request.credentials.

Giá trị trả về

Một Promise được giải quyết khi mô-đun từ URL đã cho được thêm vào. Promise không trả về giá trị nào.

Ngoại lệ

Nếu addModule() thất bại, nó từ chối promise và gửi một trong các lỗi sau đến trình xử lý từ chối.

AbortError DOMException

Script được chỉ định không hợp lệ hoặc không thể tải.

SyntaxError DOMException

moduleURL được chỉ định không hợp lệ.

Ví dụ

Ví dụ AudioWorklet

js
const audioCtx = new AudioContext();
const audioWorklet = audioCtx.audioWorklet;
audioWorklet.addModule("modules/bypassFilter.js", {
  credentials: "omit",
});

Ví dụ PaintWorklet

js
CSS.paintWorklet.addModule(
  "https://mdn.github.io/houdini-examples/cssPaint/intro/worklets/hilite.js",
);

Sau khi script đã được thêm vào paint worklet, hàm paint() của CSS có thể được dùng để bao gồm hình ảnh được tạo bởi worklet:

css
@supports (background-image: paint(id)) {
  h1 {
    background-image: paint(hollow-highlights, filled, 3px);
  }
}

Thông số kỹ thuật

Thông số kỹ thuật
HTML
# dom-worklet-addmodule-dev

Tương thích trình duyệt