JavaScript for WordPress › Forums › Vanilla JavaScript › Async scripts after jquery has been added asynchronously
- This topic has 1 reply, 2 voices, and was last updated 7 years, 3 months ago by Zac Gordon.
Viewing 2 posts - 1 through 2 (of 2 total)
-
AuthorPosts
-
July 27, 2017 at 2:23 pm #30340Jonathan BrownParticipant
Here’s some code I pieced together for loading scripts after jquery has been loaded via the async method.
var async = async || []; (function () { var done = false; // Create script element var script = document.createElement("script"), head = document.getElementsByTagName("head")[0] || document.documentElement; // Set script properties script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js'; script.type = 'text/javascript'; script.async = true; script.onload = script.onreadystatechange = function() { if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) { done = true; // console.log('jquery main script is ready'); while(async.length) { var obj = async.shift(); if (obj[0] =="ready") { $(obj[1]); } else if (obj[0] =="load"){ $(window).load(obj[1]); } } async = { push: function(param){ if (param[0] =="ready") { $(param[1]); }else if (param[0] =="load"){ $(window).load(param[1]); } } }; } }; head.insertBefore(script, head.firstChild); })(); // function to load scripts based on url value you pass in. Optional callback function. function loadScript(url, callback){ var script = document.createElement("script"); script.type = 'text/javascript'; script.async = true; script.src = url; if( callback ) { script.onload = callback; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(script, s.nextSibling); } /* * Push scripts onto async stack with ready value. * Callback's are chained to set order in which you * want scripts to be loaded */ async.push(["ready", function() { loadScript('js/build/production.js', function() { loadScript('js/app.js'); }); }]);
August 30, 2017 at 12:32 am #31125Zac GordonKeymasterHey Jonathan, thanks for sharing!
-
AuthorPosts
Viewing 2 posts - 1 through 2 (of 2 total)
- You must be logged in to reply to this topic.