0

What is the best method to enqueue scripts based on options I have? Let's say I have 50 options and for each I need to enqueue a script(some of them might repeat.). Can I have any problems(performance, etc.) if I do this in a foreach loop and switch to detect what script I need? Do you think is better than calling all scripts no matter what options I have? Like so(the class works just like I need):

<?php
class MyClass{
    var $options;

    public function __construct($options){
        $this->options = ( isset($options) ) ? $options : array();
        add_action( 'admin_enqueue_scripts', array(&$this, 'enqueue') );
    }

    //This is the section where I enqueue the scripts
    function enqueue() {
        foreach ($this->options as $value) {
            switch ($value['type']) {
                case 'value1':
                    wp_enqueue_script('value1_script');
                    break;
                case 'value2':
                    wp_enqueue_script('value2_script');
                    break;
            }
        }
    }

    function render_opts() {
        $output = '';
        foreach ($this->options as $value) {
            switch ($value['type']) {
                case 'value1':
                    $output .= 'value1';
                    break;
                case 'value2':
                    $output .= 'value2';
                    break;
            }
        }
        return $output;
    }
}
2
  • A foreach cycle through 50 items will not affect performance. But if you enqueue 50 scripts in a page with 50 different <script> tags, the page require 50 http requests to load and this will sure affect performance. Commented Oct 8, 2013 at 10:55
  • 2
    If those are all some tiny scripts, I'd go with lamzozo's suggestion. However, if some scripts are big, I'd load them conditionally. I personally like the Jedi Master Way: scribu.net/wordpress/optimal-script-loading.html Commented Oct 8, 2013 at 16:20

1 Answer 1

2

I would combine and minify all the scripts, in this case you don't have to update your php code if you add more options or scripts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.