Skip to content

Instantly share code, notes, and snippets.

@samthor
Last active February 14, 2024 02:54
Show Gist options
  • Save samthor/64b114e4a4f539915a95b91ffd340acc to your computer and use it in GitHub Desktop.
Save samthor/64b114e4a4f539915a95b91ffd340acc to your computer and use it in GitHub Desktop.
Safari 10.1 `nomodule` support
// UPDATE: In 2023, you should probably stop using this! The narrow version of Safari that
// does not support `nomodule` is probably not being used anywhere. The code below is left
// for posterity.
/**
* Safari 10.1 supports modules, but does not support the `nomodule` attribute - it will
* load <script nomodule> anyway. This snippet solve this problem, but only for script
* tags that load external code, e.g.: <script nomodule src="nomodule.js"></script>
*
* Again: this will **not** prevent inline script, e.g.:
* <script nomodule>alert('no modules');</script>.
*
* This workaround is possible because Safari supports the non-standard 'beforeload' event.
* This allows us to trap the module and nomodule load.
*
* Note also that `nomodule` is supported in later versions of Safari - it's just 10.1 that
* omits this attribute.
*/
(function() {
var check = document.createElement('script');
if (!('noModule' in check) && 'onbeforeload' in check) {
var support = false;
document.addEventListener('beforeload', function(e) {
if (e.target === check) {
support = true;
} else if (!e.target.hasAttribute('nomodule') || !support) {
return;
}
e.preventDefault();
}, true);
check.type = 'module';
check.src = '.';
document.head.appendChild(check);
check.remove();
}
}());
/**
* Minified-ish version of the above.
*/
(function() {
var d = document;
var c = d.createElement('script');
if (!('noModule' in c) && 'onbeforeload' in c) {
var s = false;
d.addEventListener('beforeload', function(e) {
if (e.target === c) {
s = true;
} else if (!e.target.hasAttribute('nomodule') || !s) {
return;
}
e.preventDefault();
}, true);
c.type = 'module';
c.src = '.';
d.head.appendChild(c);
c.remove();
}
}());
@anilanar
Copy link

anilanar commented Jun 25, 2017

Safari 10.1 still downloads the nomodule file, but it doesn't execute.

My fork: https://gist.github.com/anilanar/5be4897eb2ef261ff53a778e3fe5f2d3
Not as easy to use as the original one as scripts are injected at runtime.

@samthor
Copy link
Author

samthor commented Sep 12, 2017

Hey everyone! This approach works but has its challenges—Safari might still download the script, even though it won't execute, which is not ideal (but it is a limited version of Safari that this issue effects).

A simpler approach, although it involves adding more hacks to your actual code, is to create your ES Modules / nomodule scripts in this order:

<script type="module" src="module.js"></script>
<script src="nomodule.js" nomodule defer></script>

The key here is the defer attribute. As ES Modules scripts are deferred by default, you want your older code to run in the same way—after the page is loaded—so they will run in a consistent order.

And then inside the nomodule.js file, check whether your code has already executed: e.g. if (window._yourCodeLoaded) { throw new Error("safari 10.1 has a bug"); }.

@niklaskorz
Copy link

@samthor Would you suggest dynamically inserting a new script tag in the deferred nomodule script (in case the module script has not been loaded / the flag has not been set by the main code)?

@jacksonrayhamilton
Copy link

@samthor You're missing the closing double quote: if (window._yourCodeLoaded) { throw new Error("safari 10.1 has a bug"); }

@niklaskorz I believe setting defer on the second script guarantees that it runs after the earlier already-defer-ed script.

@GrosSacASac
Copy link

GrosSacASac commented Dec 27, 2017

/* safari 10 nomodule fix CC0-1.0
this snippet needs to be at the beginning of the 
<script type="module" src="main-as-module.js"> and associated
<script nomodule src="main-as-script.js">
by throwing an error early the rest of the code is not executed
but only downloaded and compiled for Safari 10
assumption main-as-module.js and main-as-script.js
 are both built from the same source

advantage is that there is no js file that needs to be inlined
 at the top of the html

issue: does not work with multiple indepent files without renaming the global used
 
conclusion: worse for Safari10 better for everyone else

*/
if (window.MAIN_EXECUTED) {
    // "warning main.js already executed"
    throw new Error("");
}
window.MAIN_EXECUTED = true;

https://github.com/GrosSacASac/JavaScript-Set-Up/blob/master/js/quirk_fixes/safari10_nomodule_fix.js

@fredrikpaues
Copy link

How do I use this? Should it be an inline script tag or pasted into my type="module" script tag?

@lili21
Copy link

lili21 commented Dec 24, 2018

@fredrikpaues

it should be inlined and placed before your nomodule scripts.

@lili21
Copy link

lili21 commented Feb 22, 2019

later version safari still load nomodule scirpts. I test it in iOS 12.1.4. It always load nomodule script .

@fmonteiro
Copy link

From what I tested, even with this "hack", Safari 12.0.3 always loads the nomodule.

Any news on this?

@lili21
Copy link

lili21 commented Feb 17, 2020

if you attach the event on document, it will block all subresources, and not just nomodule scripts. am i right?

@mcshaz
Copy link

mcshaz commented Apr 11, 2020

A simpler approach, although it involves adding more hacks to your actual code, is to create your ES Modules / nomodule scripts in this order:

<script type="module" src="module.js"></script>
<script src="nomodule.js" nomodule defer></script>

Using a module/nomodule approach with dynamic imports/deferred loading of polyfills and other bits of code as required - it is likely the nomodule has everything bundled into 1 large file, and the modules with dynamic imports are not yet loaded. In this scenario, it would seem best to me to to not mark the nomodule script with defer, and therefore execute this script in preference.

@frank-dspeed
Copy link

frank-dspeed commented Jun 15, 2020

The best solution is to use a script tag and then simply check for module support if module support exists add the module script tag dynamic else add the nomodule version script tag.

as script is always supported and can easy add a script module tag this is the way to go.

<script>
(function() {
  var loadScript = document.createElement('script')
  var esmVersion = './module.mjs'
  var cjsVersion = './module.js'

  if (!'noModule' in HTMLScriptElement.prototype) {
     loadScript.src = cjsVersion
  } else {
     loadScript.type = 'module'
     loadScript.src = esmVersion
  }

  document.body.append(loadScript)
})()
</script>

@ChrisMcKee
Copy link

in use on the BBC site view-source:https://www.bbc.co.uk/news/world-europe-54002880

@frank-dspeed
Copy link

@ChrisMcKee what is in use?

@sno2
Copy link

sno2 commented Oct 15, 2020

@ChrisMcKee what is in use?

Go to view-source:https://www.bbc.com/news/world-europe-54002880 if you use Chrome, or go to https://www.bbc.com/news/world-europe-54002880 and select view source code. Next, do find in page (CTRL/CMD + F) and search for https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc (the gist link for sourcing the author). You can then see that BBC News is using this gist within their code! I am quite surprised, though, as they aren't removing the whitespace from the code that is rendering on all of their pages. It's probably a licensing issue.

@frank-dspeed
Copy link

@CodingCarter oh ok why not who cares :) it is free to use

@tim-247
Copy link

tim-247 commented Apr 1, 2021

@ChrisMcKee what is in use?

Go to view-source:https://www.bbc.com/news/world-europe-54002880 if you use Chrome, or go to https://www.bbc.com/news/world-europe-54002880 and select view source code. Next, do find in page (CTRL/CMD + F) and search for https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc (the gist link for sourcing the author). You can then see that BBC News is using this gist within their code! I am quite surprised, though, as they aren't removing the whitespace from the code that is rendering on all of their pages. It's probably a licensing issue.

What would be the licensing issue?

@sno2
Copy link

sno2 commented Apr 1, 2021

@ChrisMcKee what is in use?

Go to view-source:https://www.bbc.com/news/world-europe-54002880 if you use Chrome, or go to https://www.bbc.com/news/world-europe-54002880 and select view source code. Next, do find in page (CTRL/CMD + F) and search for https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc (the gist link for sourcing the author). You can then see that BBC News is using this gist within their code! I am quite surprised, though, as they aren't removing the whitespace from the code that is rendering on all of their pages. It's probably a licensing issue.

What would be the licensing issue?

Many companies just don't modify the code via minification because if the code is actually under a stricter license such as GPL-3 then they have to state their changes.

@samthor
Copy link
Author

samthor commented Apr 6, 2021

FWIW I've added an Apache-2.0 license at the top of this file for anyone who is concerned about that.

@aanand07
Copy link

Hey everyone! This approach works but has its challenges—Safari might still download the script, even though it won't execute, which is not ideal (but it is a limited version of Safari that this issue effects).

A simpler approach, although it involves adding more hacks to your actual code, is to create your ES Modules / nomodule scripts in this order:

<script type="module" src="module.js"></script>
<script src="nomodule.js" nomodule defer></script>

The key here is the defer attribute. As ES Modules scripts are deferred by default, you want your older code to run in the same way—after the page is loaded—so they will run in a consistent order.

And then inside the nomodule.js file, check whether your code has already executed: e.g. if (window._yourCodeLoaded) { throw new Error("safari 10.1 has a bug"); }.

To avoid adding a new property in window for browsers other than safari 10.1 may be can check for safari 10.1 before adding the global property

var check = document.createElement('script');
  if (!('noModule' in check) && 'onbeforeload' in check) {
      if (window._yourCodeLoaded)  throw new Error("safari 10.1 has a bug"); 
      window._yourCodeLoaded = true;
  }

@devilmancbc
Copy link

why appendChild(check) and remove it?

@devilmancbc
Copy link

why (e.target === check),can prove support 'type=module' ?
the support variable seems to have never been used by anyone ?
Thanks for help:)

@gtempesta
Copy link

gtempesta commented Sep 14, 2023

Is it safe to stop using this script? I'm doing differential serving with the following browserslist queries:

  • > 0.25% and not supports es6-module for legacy browsers
  • > 0.25% and supports es6-module, not dead, Firefox ESR for the modern ones

Safari is not included in the first list, while the second one only includes Safari from 14.1 to 16.6, so I guess I'm not supporting Safari 10.1 at all. Is my assumption correct or do you still recommend we include the script?

@samthor
Copy link
Author

samthor commented Sep 15, 2023

This code is ancient, stop using it.

The narrow window of Safari that is broken here is likely not being used anywhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment