Disclaimer: It is possible to generate polyglots with more flexibility by using different charsets. Below there is a simple PoC to create GIFJS files with both UTF-8 and UTF-16 (I will be adding more when I have time).
The main point is the more charsets supported, the more flexibility. Since the image may have different constraints in terms of size or specific bytes, we can play with different encodings (preferably multi-byte) and with different HIDDING bytes, until the image fits.
The term HIDDING bytes refers to the chars that make possible skipping the image binary streams to the JS parser, for instance:
//, etc. I've tried to parameterize the image creation to make this step as flexible as possible.
Anyway, this is just a dirty PoC, breaks many times and the code is ugly as fuck, so be kind...