Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simulate fbasyncInit behaviour on a webpack bundled library

Im using webpack to build a library targeted for browsers. And i Would really like to replicate fbasyncinit behavior without manually modyfing the bundled library.

Does webpack provide any way to call a function after loading the library itself ?

Or is there another alternative bundler that allows this?

For those unnaware, window.fbasyncinit is a function facebook sdk calls when finish loading, so you write the function to initialize facebook sdk stuff.

like image 282
Illiax Avatar asked Dec 20 '18 17:12

Illiax


1 Answers

Depending on your setup you might want to make your library external and lazy load it into the target application. In a nutshell this means that your library exists alongside the application but won't actually be loaded on initialization. It could then be loaded by an event or after some setTimeout.

Webpack watches for special comments to tell it what code needs to be separated into its own bundle:

button.onclick = event => {
    const loadLodash = await import(/* webpackChunkName: "lodash" */ "lodash");
    console.log('lodash loaded');
};

This kind of comment,/* webpackChunkName: "lodash" */, is one such type. Note that until whatever event or timeout occurs, your library will not be loaded.

To be honest I haven't done this for libraries in particular so I'm not sure of the difficulties this might impose here.

Update

Actually, there might be a simpler answer to this. I forgot that lazy loading is actually just dynamically creating a script tag with a src to the library you want to load (using a bundled lodash library for example).

var script = document.createElement('script');
script.src = 'http://localhost:8080/vendors.[hash].js';
document.head.appendChild(script);

If you need to control when your library is loaded you could just trigger it this way after some other code (something that just exists to load the library) detects a page load.

Update 2

After rereading this, it may also be just as simple as triggering your fbasyncinit simulated behavior after some event when you know the library is loaded into the app (assuming your library doesn't depend on any network calls to initialize). All of the other ideas apply as well, but may be more complicated than you need. Before trying the external/lazy-load solutions I'd suggest looking at something simple like this within your library:

window.addEventListener('load', event => {
    // your custom fbasyncinit behavior here
});

This is of course after everything in the page has been loaded, which may be too late depending on your needs.

like image 186
GenericUser Avatar answered Nov 14 '22 00:11

GenericUser