@animech-public/playcanvas
Version:
PlayCanvas WebGL game engine
2 lines (1 loc) • 1.86 kB
JavaScript
import{platform as t}from"../../core/platform.js";import{script as e}from"../script.js";import{ScriptTypes as s}from"../script/script-types.js";import{registerScript as o}from"../script/script-create.js";import{ResourceLoader as r}from"./loader.js";import{ResourceHandler as a}from"./handler.js";import{Script as i}from"../script/script.js";class c extends a{constructor(t){super(t,"script"),this._scripts={},this._cache={}}clearCache(){for(const t in this._cache){const e=this._cache[t],s=e.parentNode;s&&s.removeChild(e)}this._cache={}}load(t,o){"string"==typeof t&&(t={load:t,original:t});const a=this;e.app=this._app;const i=(t.load,(t,i,c)=>{if(t)o(t);else if(e.legacy){let t=null;s._types.length&&(t=s._types.pop()),t?this._scripts[i]=t:t=null,o(null,t,c)}else{const t={};for(let e=0;e<s._types.length;e++)t[s._types[e].name]=s._types[e];s._types.length=0,o(null,t,c),delete a._loader._cache[r.makeKey(i,"script")]}}),[c]=t.load.split("?");c.endsWith(".mjs")?this._loadModule(c,i):this._loadScript(t.load,i)}open(t,e){return e}patch(t,e){}_loadScript(t,e){const s=document.head,o=document.createElement("script");this._cache[t]=o,o.async=!1,o.addEventListener("error",(t=>{e(`Script: ${t.target.src} failed to load`)}),!1);let r=!1;o.onload=o.onreadystatechange=function(){r||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(r=!0,e(null,t,o))},o.src=t,s.appendChild(o)}_loadModule(e,s){const r=t.browser?window.location.origin+window.location.pathname:import.meta.url,a=new URL(e,r);import(a.toString()).then((t=>{const r=a.pathname.split("/").pop(),c=this._app.assets.find(r,"script").data.scripts;for(const e in t){const s=t[e];if(s.prototype instanceof i){const t=(p=s.name)[0].toLowerCase()+p.substring(1);o(s,t),this._app.scripts.addSchema(t,c[t])}}var p;s(null,e,null)})).catch((t=>{s(t)}))}}export{c as ScriptHandler};