Skip to content

Instantly share code, notes, and snippets.

@jmschrack
Created November 9, 2022 22:24
Show Gist options
  • Save jmschrack/a3fa800c644b2cd32ec0c57d5ac9809a to your computer and use it in GitHub Desktop.
Save jmschrack/a3fa800c644b2cd32ec0c57d5ac9809a to your computer and use it in GitHub Desktop.
Two helper scripts that will let you add external libraries or modules to the threejs.org/Editor tool.
/*
## Add External JS libraries ##
This function will inject a new `<script />` tag into the header of the page.
You can specify the id, url, and onload events. If it detects the ID already exists, it aborts which makes it safe to use in the Editor.
*/
function SafeAddScriptSrc(id,url,onload){
if(document.getElementById(id)==null){
console.log('SafeAddScriptSrc::'+id+' Adding...');
var newScript = document.createElement('script');
newScript.onLoad=onload;
newScript.id=id;
newScript.src=url;
newScript.async = true;
document.head.appendChild(newScript);
return false;
}else{
console.log('SafeAddScriptSrc::'+id+' Found!');
return true;
}
}
/*
##Sample Usage:##
```
SafeAddScriptSrc('TWEENScript',
"//cdnjs.cloudflare.com/ajax/libs/tween.js/16.3.5/Tween.min.js",
function(){console.log("TWEEN loaded");});
function update( event ) {
if(window.TWEEN)
TWEEN.update();
}
```
*/
/*
## Import a class from an external module ##
This function will inject a new `<script type="module"/>` tag into the header of the page.
It will immediately import the module, and set it at window.modules['moduleName'] so it can be accessed wherever.
*/
function SafeAddModuleSrc(moduleName,url,onload){
let id=moduleName+'_Module';
if(typeof(window.modules)=="undefined")
window.modules={};
if(document.getElementById(id)==null){
console.log('SafeAddModuleSrc::'+id+' Adding...');
var newScript = document.createElement('script');
newScript.onLoad=onload;
newScript.id=id;
newScript.type='module';
//newScript.src=url;
newScript.async = true;
newScript.text=`import * as ${moduleName} from '${url}';window.modules.${moduleName}=${moduleName}; `;
document.head.appendChild(newScript);
return false;
}else{
console.log('SafeAddScriptSrc::'+id+' Found!');
onload();
return true;
}
}
/*
##Sample Usage##
```
SafeAddModuleSrc('FirstPersonControls','./jsm/controls/FirstPersonControls.js');
```
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment