Delayed JS loading

Based on http://www.stevesouders.com/blog/2009/09/26/mobile-gmail-and-async-script-loading/ comments. But event simpler – no code processing at all, though doubling the DOM which might be bad for big scripts.

But nevertheless.

1) add the script with some fake type and some meaningful ID:

<script type="delayed" id="delayed">
function fix() {
    document.getElementById("s").innerHTML = "222"
}
alert(1)
</script>
1
2
3
4
5
6
<script type="delayed" id="delayed">
function fix() {
    document.getElementById("s").innerHTML = "222"
}
alert(1)
</script>

2) turn it into a real script on demand by calling this trivial function:

function load(id) {
	var el = document.createElement("script");
	el.innerHTML = document.getElementById(id).innerHTML;
	document.body.appendChild(el);
}
1
2
3
4
5
function load(id) {
	var el = document.createElement("script");
	el.innerHTML = document.getElementById(id).innerHTML;
	document.body.appendChild(el);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Notify me of followup comments via e-mail. You can also subscribe without commenting.