How to defer or load an A-Frame scene programmatic

2019-04-14 10:44发布

问题:

I have an A-Frame scene that I want to place on a page, but I want it to load only when I tell it to. That means it should not be rendering or running until I emit an event or call a method.

<body>
  <!-- Don't play yet. -->
  <a-scene>
  </a-scene>
</body>

回答1:

There is currently no built-in + documented way, but there will be a feature for this later. However, there are a couple ways to do this manually:

Create <a-node>

Nodes (which every <a-entity> inherits from will block the scene from loading until it calls the .load() event.

Create a dummy node in the scene. and call .load() when ready.

<a-node id="dummy"></a-node>

document.getElementById('dummy').load();

Leverage asset system

You can create an asset that will never load until you tell it to, and set the timeout to effectively indefinite (later we will add a feature to not timeout).

<a-scene>
  <a-assets timeout="999999999">
    <a-asset-item id="trigger" src="NEVERLOADUNTILITELLITTO.whatever"></a-asset-item>
  </a-assets>
</a-scene>

Then trigger.

document.querySelector('#trigger').load();

Inject scene only when ready

You could keep your scene in a separate file, template, or as a string, or using a framework with concept of Views. Only inject the scene into the DOM when you are ready for it to render. This is the most work, but currently the most air-tight method.

sceneEl.appendChild(document.createRange().createContextualFragment(str));

Pause the scene as soon as you can

This will pause the scene from rendering. However, the scene will probably have initialized some components and rendered a few frames already. So it is not air-tight.

document.querySelector('a-scene').pause();


标签: aframe