Optimize custom snippet injection/developing workflow

This is more a post about my findings working with the custom footer script injection.

Now the first problem with the custom footer and e.g. the custom flat rate snippet is that, it gets injected every time the cart rerenders itself. This will let you end with endless script inclusion each own with its own callback to the shipping handling. This slows down the entire page. I wanted to not only fix that but also to make my development workflow better

The solution:
I'm using the following custom footer
{% if (context == 'cart' or context == 'checkout') and item_count > 0 %}
<script type="text/javascript" charset="utf-8">

window.boxShop = window.boxShop || {JSInjected:false};

if(!window.boxShop.JSInjected){
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.onload = function(){
//Here i'm using the custom flat rate snippet, just remove the code if you do not need to call something. Why did i put the code here instead of the myfoxy.js file? Because here i'm able to use the twig template variables :)
{% if cart_is_fullpage or context == 'checkout' %}
FC.customFlatRates.requireShipping();
{% else %}
FC.customFlatRates.requireShipping(); //leads to double api calls, but needed for initial calculation for a new cart
{% endif %}
};
script.src = 'https://YOUR-LOCAL-WEB-SERVER-OR-REMOTE-SERVER/myfoxy.js'; //If you want to include this and test your checkout page, of course you need to upload it to an ssl supported server, your local web server is not reachable from foxycart.com
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
window.boxShop.JSInjected=true;
}
</script>
{% endif %}


First it only injects the custom script once on the page. Second it enables you to inject your local myfoxy.js file into your page, so whenever you change that file, you can just hit f5 and have your changes ready to rock :)
Tagged:
Comments
  • fc_adamfc_adam FoxyCart Team
    @fileee,

    Thanks for sharing! We do have a ticket for correcting the Sidecart custom footer inclusion to prevent it from being included in the re-renders - your solution there will work great for the interim.
  • Great to hear.

    One more thing if anyone sees this. For production release, you can ommit the whole script injection and just place your custom script between
    if(!window.boxShop.JSInjected){
    //Place your custom code here
    window.boxShop.JSInjected=true;
    }
Sign In or Register to comment.