Instantly share code, notes, and snippets.

What would you like to do?
Simply mimic the 'defer' attribute for inline scripts across all browsers (jQuery helper)
<!-- Somewhere along your page, you have some javascript which you want to defer. Just set its type to text/javascript/defer -->
<script type="text/javascript/defer">
$('body').css('background', 'green');
<!-- maybe even an external file -->
<script type="text/javascript/defer" src=""></script>
<!-- then near the bottom, you load libraries & dependencies like you should -->
<script src=""></script>
<!-- Assuming one of them is jQuery, just add this thingy and voila! Your scripts will run on `ready`. Note: Execution order isn't guaranteed for external files -->
<!-- Unminified, if you're interested:
$(this).clone().attr('type', '').insertAfter(this);

This comment has been minimized.

Copy link

bryanwillis commented Jan 9, 2016

Hey looks cool. I see that this is four years old. Is this still a good solution for deferring inline scripts dependent on jQuery?


This comment has been minimized.

Copy link

wizzwizz4 commented Apr 12, 2018

It was never a great solution, since jQuery has to be undeferred in order for it to work (unless you have this script external and then defer it). If reimplemented in plain JavaScript it still wouldn't be great, since text/javascript/defer isn't a valid value for type (though most web browsers will just "deal with it"). If changed to use a data- attribute, the only problem I can see is that it doesn't seem to stop the JavaScript from running initially, so if you had something like:

<script type="text/javascript/defer">
  var x = document.getElementById("example").textContent;
  document.getElementById("example").textContent = "";

then it would wipe the contents of #example before performing an HTML eval on the contents, since it could only perform that HTML eval the second time when it was run with jQuery present. Also there'd be a lot of errors posted to the console and not a lot you could do about it.

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