utils.js (2204B)
1 globalThis.assertSpeculationRulesIsSupported = () => { 2 assert_implements( 3 'supports' in HTMLScriptElement, 4 'HTMLScriptElement.supports must be supported'); 5 assert_implements( 6 HTMLScriptElement.supports('speculationrules'), 7 '<script type="speculationrules"> must be supported'); 8 }; 9 10 // If you want access to these, be sure to include 11 // /html/browsers/browsing-the-web/remote-context-helper/resources/remote-context-helper.js. 12 // So as to avoid requiring everyone to do that, we only conditionally define this infrastructure. 13 if (globalThis.RemoteContextHelper) { 14 class PreloadingRemoteContextWrapper extends RemoteContextHelper.RemoteContextWrapper { 15 /** 16 * Starts preloading a page with this `PreloadingRemoteContextWrapper` as the 17 * referrer, using `<script type="speculationrules">`. 18 * 19 * @param {"prefetch"|"prerender"} preloadType - The preload type to use. 20 * @param {object} [extrasInSpeculationRule] - Additional properties to add 21 * to the speculation rule JSON. 22 * @param {RemoteContextConfig|object} [extraConfig] - Additional remote 23 * context configuration for the preloaded context. 24 * @returns {Promise<PreloadingRemoteContextWrapper>} 25 */ 26 addPreload(preloadType, { extrasInSpeculationRule = {}, ...extraConfig } = {}) { 27 const referrerRemoteContext = this; 28 29 return this.helper.createContext({ 30 executorCreator(url) { 31 return referrerRemoteContext.executeScript((url, preloadType, extrasInSpeculationRule) => { 32 const script = document.createElement("script"); 33 script.type = "speculationrules"; 34 script.textContent = JSON.stringify({ 35 [preloadType]: [ 36 { 37 source: "list", 38 urls: [url], 39 ...extrasInSpeculationRule 40 } 41 ] 42 }); 43 document.head.append(script); 44 }, [url, preloadType, extrasInSpeculationRule]); 45 }, 46 extraConfig 47 }); 48 } 49 } 50 51 globalThis.PreloadingRemoteContextHelper = class extends RemoteContextHelper { 52 static RemoteContextWrapper = PreloadingRemoteContextWrapper; 53 }; 54 }