Skip to content

Instantly share code, notes, and snippets.

@RichardTMiles
Last active January 18, 2018 08:50
Show Gist options
  • Save RichardTMiles/851ed048b7939e7c01942a12ebe27445 to your computer and use it in GitHub Desktop.
Save RichardTMiles/851ed048b7939e7c01942a12ebe27445 to your computer and use it in GitHub Desktop.
Dynamic Javascript Inclusion using LoadJS and PJAX. Loading javascript files on call time when refreshing with Ajax.
<html> // This was chopped from https://carbonphp.com , a php framework which incorporates PJAX and and HTML5 Sockets
<head>
<script>
/*! loadJS: load a JS file asynchronously. [c]2014 @scottjehl, Filament Group, Inc. (Based on http://goo.gl/REQGQ by Paul Irish). Licensed MIT */
(function (w) {
let loadJS;
loadJS = function (src, cb) {
"use strict";
let ref = w.document.getElementsByTagName("script")[0];
let script = w.document.createElement("script");
script.src = src;
script.async = true;
ref.parentNode.insertBefore(script, ref);
if (cb && typeof(cb) === "function")
script.onload = cb;
return script;
}; // commonjs
if (typeof module !== "undefined") module.exports = loadJS;
else w.loadJS = loadJS;
}(typeof global !== "undefined" ? global : this));// Hierarchical PJAX Request
// Your new document ready function
function Carbon(cb) {
document.addEventListener("Carbon", function fn(event) {
document.removeEventListener("Carbon", fn);
cb(event);
});
}
</script>
</head>
<body>
<!-- Pjax content-->
<article>
<!-- Example Page -->
Carbon(()=> { <!-- Your Code Here -->
$.fn.load_datatables(.mytable);
});
<!--./Example Page -->
</article>
<!-- ./Pjax content -->
<script>
loadJS('Jquery.js', () => { // include jQuery
loadJS('PJAX.js', () => { // include PJAX
$(document).pjax('a', 'article'); // All links will be sent with ajax
let JSLoaded = new Set();
$.fn.CarbonJS = (sc, cb) => (!JSLoaded.has(sc) ? loadJS(sc, cb) : cb());
//-- Data tables -->
$.fn.load_datatables = (table) =>
$.fn.CarbonJS("dataTables.bootstrap.js", () => {
try { return $(table).DataTable() } catch (err) { return false }});
//-- iCheak -->
$.fn.load_iCheck = (input) => {
$.fn.CarbonJS("icheck.min.js", () => {
$(input).iCheck({
checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional
});
});
};
// Create Events
$.fn.runEvent = (ev) => {
let event;
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent(ev, true, true)
} else {
event = document.createEventObject();
event.eventType = ev
}
event.eventName = ev;
document.createEvent ? document.dispatchEvent(event) :
document.fireEvent("on" + event.eventType, event);
};
// run scripts wrapped in our Carbon function
$(document).on('pjax:complete', () => $.fn.runEvent("Carbon"));
})
});
</script>
</body>
</html> // Your welcome ;)
@RichardTMiles
Copy link
Author

RichardTMiles commented Jan 18, 2018

The key here is that you need to make sure no race conditions are present and that files are loaded when needed.
I personally dont use the caching feature built into PJAX, as my website is fully dynamic. You can achive this too by adding

$(document).on('pjax:popstate', () => $.pjax.reload(selector));    // refresh our state always!!

Just remember to change the selector.

The Filament Group killed the loadJS() function, but for css use google #cuz_google
https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

I use load js because I desired a fully async load that fully controlled in order. Simply put, I need the jQuery file to load before PJAX. My personal script tag is at the bottom of the page like the example above; however it contains many more cascading js includes.

The Script in the head "Carbon()" accepts a function argument and attaches a one time eventlistener to it. This became essential when changing pages with a popstate. No since in running the Datatables script after we've moved pages.

Developing in PHP... Skip the setup by using Carbonphp.com

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