theodi/open-data-certificate

Asynchronous badge JS

Opened this issue ยท 5 comments

Reported by user:

We've had intermittent problems with the page load being held up by the badge.js script taking a long time to load. At its best, it seems to take around 450ms to load the script, but it's often longer than that.

Since the badge isn't a critical part of the UX of the page, I'd like to be able to load it asynchronously. That way, the badge script shouldn't hold up the page-ready event. However, at the moment the script uses document.write() to add content to the page, so if I do:

<script 
  async 
  src='https://certificates.theodi.org/datasets/132/certificates/14290/badge.js'>
</script>

I get an error:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

Could you please extend or improve the badge.js script to support asynchronous access to the DOM? Or, if you have already enabled this, please let me know what changes I need to make at my end?

I guess the ideal thing would be to have the thing accept an ID to put the content into, then set it up to go in asynchronously.

It's possible to use document.currentScript to replace the script tag asynchronously.

I might be able to put in a PR later this week if that'd help? (I feel slightly responsible for letting that document.write in there in the first place!)

@benfoxall that would be amazing! I'd have to brush up my JS to be sure of getting it right, so if you can... ๐Ÿ˜

@Floppy cool! I'll try and take a look in the next couple of days ๐Ÿ‘