Reputation: 5000
I am going to write a small charting library (with chart types such as bar, pie, line etc.) to be used in a WordPress context. The library might depend on external libs such as D3.js, underscore.js etc. Ideally, I would not have to include all chart and all dependencies on each page.
What is a good way of managing the instantiation of these charts across WordPress pages and posts and the loading of their dependencies? Require.js examples, native WP loading resources or similar are much welcome.
Thanks.
Upvotes: 1
Views: 294
Reputation: 2953
Look at WordPress's wp_enqueue_script and wp_enqueue_style functions. It's the recommended method for linking scripts and styles to a page. You could create a custom function, with a conditional statement that checks which page template or page is being displayed, and loads the relevant scripts accordingly. This way you're not loading them on every page.
function load_my_scripts() {
if (is_page('Charts')) {
wp_register_script('custom_script', 'path/to/script/',, '1.0', true);
wp_enqueue_script('custom_script')
}
}
add_action( 'wp_enqueue_scripts', 'load_my_scripts' );
Note: the wp_enqueue
function also has a parameter for dependencies. See the Codex page for more details. The 'true' at the end tells it to load the scripts in the footer, before the closing </body>
tag
Upvotes: 1