In my website I have many inline javascript snippets. Most of them require jquery and similar stuff.
But I would like to defer jquery load to after the page was rendered. And that means, that my inline javascript would execute, before jquery was loaded. Is there anything I can do about it? I am looking for easy to implement solutions (I also cannot move my inline javascript since it is automatically generated while page is being prepared for the user).
Inline JavaScript executes in the order in which it appears in the page. There's no “deferring” it. As a result, if something in there relies on jQuery, it'll simply throw an error to the console log and refuse to execute.
Scripts with the defer attribute will execute in the order in which they appear in the document. This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse.
The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM. The script loads “in the background”, and then runs when the DOM is fully built.
You should use defer for all other scripts. defer is great because it: Gets loaded as soon as possible — so it reduces load times. Doesn't execute until everything you need is ready — so all the DOM you need is there.
It would be much better if you could place your javascript at the end of the document. Sprinkling your source with small inline javascript snippets is a killer on page performance.
That said, you could create an array and push functions on this array. Then, at the end of your page, right after you load jquery, loop over the array and execute each function.
E.g.:
<html>
...
<script>window.loadEvents = [];</script>
...
<script>loadEvents.push(function() { alert("inline code here"); });</script>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>$.each(loadEvents, function(_,f) { f(); });</script>
</html>
However - as I said - it would be better to just push all the script elements into the bottom of the page, instead of switching back and forth between html and javascript. The rendering performance will be severely degraded, if you do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With