objecthub-io / ObjectHub

ObjectHub is an open repository for software objects and a development platform.
2 stars 1 forks source link

Loading of asynchronous scripts #283

Closed michaelbukachi closed 7 years ago

michaelbukachi commented 7 years ago

Hello. I was wondering, how would one load asynchronous libraries, for instance. Google maps. It seems micro apps have their own loading time. So you end up in a situation where a library is loaded asynchronously and it tries to look for an element before it's ready in the DOM. Is there a callback I can utitlize??

michaelbukachi commented 7 years ago

I figured it out. Basically, you just append the script to the body in the default wrapper when the app is loaded, as shown below:

try {
                                // load Micro App
                                var op = Apps.embed({
                                    app: client.link('%%%app_uri%%%', '%%%app_secret%%%'),
                                    wrappedApp: client.link('%%%wrapped_app_uri%%%', '%%%wrapped_app_secret%%%'),
                                    elem: $("[data-role='embed-app']"),
                                    framework: framework,
                                    parent: "noparent",
                                    root: root,
                                    server: server
                                });

                                op.catchExceptions(exCb);

                                op.get(function(app) {
                                    // LOAD SCRIPT HERE
                                    var script = document.createElement('script');
                                    script.src = 'https://maps.googleapis.com/maps/api/js?key=[API_KEY]&callback=initMap';
                                    document.body.appendChild(script);
                                    // app successfully loaded 

                                    // %%%on_load%%%
                                }); 
                            } catch (e) {
                                exCb(e);   
                            }
objecthub-io commented 7 years ago

Thank you for this question.

How you describe it, it works fine. To make things easier, you can use the Libraries.requireExternal() method which is available for Micro Apps and Micro Libraries.

Note there is another method Stylesheets.require() which can be used to load stylesheets when required.

michaelbukachi commented 7 years ago

It does make things easier.