script and css to load on the page

Script to run on every page of your database

To extend database functionality even further we’ve added an ability to run custom script on every page of your database. To keep in line with dbstyles.css logic all you need is to place dbscript.js in your database’s resources section.

As the script file is loaded and executed asynchronously, its exact execution time is not known and may happen prior to page is fully loaded. If you are going to transform page content with script code, you may need to postpone code execution to later time. You can rely on jQuery facilities to do that:

jQuery(function() { 
    // here page load is complete
    // insert some content on top of every page
    jQuery("#td-bodyframe").prepend("<p>This will appear below tabs and above page's content</p>");
});

Limit script execution scope

Body tag of each page has an identifier built from the name of the page and table’s internal identifier, say, overview_t_909. You can use CSS selectors – the same way you can do it with dbstyles.css – to limit script execution to some contexts using jQuery.

jQuery(function() { 
    if(jQuery("body[id^="overview"]").length) {
        // this will run on every overview page, but not on views and forms
    }
    if(jQuery("body[id$="_t_909"]").length) {
        // this will run on any page in Invoice table
    }
    if(jQuery("body#overview_t_909").length) {
        // this will run on overview page of Invoice table
    }
});

Load external libraries

If you need external libraries, you can rely on FS.addScript(url, callback) function to request library script and execute the code after library is loaded:

FS.addScript("//maps.googleapis.com/maps/api/js", function() {
    // do Google Maps stuff
});

Real world example

Say, you want to run Google Analytics. Simply place their code without surrounding script tags to your dbstyles.js – with modified tracking ID of course.

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

Enjoy!

Tweet about this on TwitterShare on Facebook5Share on Google+0

2 thoughts on “Script to run on every page of your database

Comments are closed.