jquery - Load javascript in consecutive order after browser load event -
what trying do? in attempt speed website loading non-essential javascript after browser load event. (so js files not render blocking) functioning correctly.
what problem? problem non-essential javascript depends on other libraries , plus libraries need load first.
what have tried fix problem? in attempt fix problem have added delay event library dependent javascript. while works sometimes, load times of js file varies between refreshes , @ times can load before library delay.
question: know of better way me load js files after first js file has loaded? (see code below)
<script type="text/javascript"> function downloadjsatonload() { var element = document.createelement("script"); var element2 = document.createelement("script"); var delay=40; element.src = "http://119.9.25.149/sites/all/themes/bootstrap/bootstrap_nova/js/highcharts.js"; element2.src = "http://119.9.25.149/sites/all/themes/bootstrap/bootstrap_nova/js/future-plastic.js"; document.body.appendchild(element); settimeout(function(){ document.body.appendchild(element2); },delay); } if (window.addeventlistener) window.addeventlistener("load", downloadjsatonload, false); else if (window.attachevent) window.attachevent("onload", downloadjsatonload); else window.onload = downloadjsatonload; </script>
as can see above, trying load highcharts js file before load future-plastic file.
you're not first have problem, thankfully. there's lot of difficult solutions around problem, including using module loader suggested in comment (which agree best long term solution, because account more browsers , flexibility, it's lot learn solve 1 small problem).
the place start learning problem , ways tackle on web. pretty resource: http://www.html5rocks.com/en/tutorials/speed/script-loading/
you may want try defer if don't have support opera mini or ie9. or, can load sync , execute loads- examples this:
[ '//other-domain.com/1.js', '2.js' ].foreach(function(src) { var script = document.createelement('script'); script.src = src; script.async = false; document.head.appendchild(script); });
the reason why might work (different browser implement differently) because default load dynamically generated script tags set async default, if set false: "they’re executed outside of document parsing, rendering isn’t blocked while they’re downloaded"
Comments
Post a Comment