Giter Club home page Giter Club logo

async-script-loader's Introduction





Async Script Loader

js-standard-style

Allows asynchronous loading of scripts and styles in a Single Page Application (or anything else, in fact):

  • Using a test to ensure that the code is only loaded once
  • Running a callback once the script is loaded
  • Running a callback if the script is already loaded
  • Not blocking the main thread

Reasoning

Having integrated a multitude of third-party SDKs from large, well known providers, I've come to the conclusion that not having a standard interface turns the whole thing into a minefield of callbacks, timers, random library-specific loader modules, and global objects on the window, resulting in XSS risks and all sort of other undesirable behaviour. This module aims to provide a standard way of loading third-party dependencies.

Usage

You pass a list of urls to the loader, along with a method for checking that your page is ready, and a callback to call when it is.

Urls can be scripts or stylesheets.

Script Tags

You can use the module like so, for a library loaded from example.com, which, when loaded, adds an attribute called PROVIDER to the global window object.

<script>
  import loader from '@beyonk/async-script-loader'

  const url = '//example.com/sdk/1.0.0/lib.js'

  function test () {
    return !!window.PROVIDER
  }

  function callback () {
    window.PROVIDER.someFunction()
  }

  loader([
    { type: 'script', url }
  ], test, callback)
</script>

You can pass options for script tags.

<script>
  loader([
    { type: 'script', url, options: { async: true, defer: true } } // these are the default options
  ], test, callback)
</script>

Style Tags

You can include any number of tags, including style tags.

When the last one has loaded, the callback will be called.

<script>
  import loader from '@beyonk/async-script-loader'

  loader([
    { type: 'script', url: '//example.com/sdk/1.0.0/lib.js' },
    { type: 'script', url: '//example.com/sdk/1.0.0/lib2.js' },
    { type: 'style', url: '//example.com/sdk/1.0.0/style.css' }
  ], () => {
    return !!window.PROVIDER
  }, () => {
    window.PROVIDER.someFunction()
  })
</script>

No more tears!

Inline scripts / Inline css

You can use inline content for either type of tag by passing the configuration attribute content instead of url. This will write the content passed into the tag's body rather than setting it as an href or src attribute url will always take prescidence, so leave it out for content to work.

<script>
  import loader from '@beyonk/async-script-loader'

  loader([
    { type: 'script', content: 'console.log("foo");' },
    { type: 'style', content: '* { color: red; }' }
  ],
  () => false, // always load
  () => () // no-op
)
</script>

async-script-loader's People

Contributors

ahpercival avatar antony avatar singingwolfboy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

async-script-loader's Issues

SyntaxError: Unexpected token 'export'

[freedom:~/m13/repo/xxx] sergio$ npm run dev

> [email protected] dev /Users/sergio/m13/repo/xxx
> sapper dev

✔ server (769ms)
✔ client (941ms)
/Users/sergio/m13/repo/xxx/node_modules/@beyonk/async-script-loader/index.js:1
export default function (url, test, callback, options = { async: true, defer: true }) {
^^^^^^

SyntaxError: Unexpected token 'export'
    at wrapSafe (internal/modules/cjs/loader.js:1072:16)
    at Module._compile (internal/modules/cjs/loader.js:1122:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (/Users/sergio/m13/repo/xxx/__sapper__/dev/server/server.js:10:30)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
> Server crashed
✔ service worker (22ms)

What have I done incorrectly?
I just copied https://github.com/beyonk-adventures/svelte-social-auth/blob/master/src/google-auth/GoogleAuth.svelte on my own folder and tried to execute once I installed this dependency

Defer loading after the page has been completely rendered

In the README it says:

You pass a list of urls to the loader, along with a method for checking that your page is ready, and a callback to call when it is.

The method for checking if the page is ready seems to be actually the method that is checking if the library has loaded, for not loading it twice (the test method).

Is there a way for deferring the loading of the script only after the page has been completely loaded? This is useful for page load speed.

Very nice library, simple and useful - Thanks!

Suggestion: allow other attributes in options besides async and defer

A common use case with third-party libraries is they expect to have an id, something like

<script id="exampleScript123" src="https://example.com/somefile.js" async defer="defer"></script>

Sometimes data attributes are requested as well:

<script data-something="exampleData" src="https://example.com/somefile.js" async defer></script>

In these cases, I use svelte:head, but it would be nice to have this use case handled by this great tool ... if you'd like a PR maybe I can do one up for you.

loader([
    { type: 'script', url, options: { id: "exampleScript123", data-something: "exampleData" } }
  ], test, callback)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.