12

how to load external JS file into moodle ? using moodle api ,i.e moodle libraries ..

shox
  • 1,150
  • 5
  • 18
  • 32

2 Answers2

19

In Moodle 2.0 I have always used $PAGE->requires->js().

To start with, make $PAGE available to your code by doing:

require_once($CFG->libdir . '/pagelib.php');
global $PAGE;

and then in your code:

$PAGE->requires->js( new moodle_url($CFG->wwwroot . '/blocks/your_block/script.js') );

It is required to put moodle_url() around your path!

franzlorenzon
  • 5,845
  • 6
  • 36
  • 58
Anatai
  • 456
  • 4
  • 7
  • How is using "$PAGE->requires->js()" better than directly adding " – iankit Jan 26 '14 at 15:53
  • 3
    @iankit it is better (and allows pages to load much faster) for several reasons: a) It avoids loading the same script repeatedly - if four different blocks all use jquery, there's no need to load the jquery library four times. b) It may avoid loading it at all until it's needed - your block probably won't be clicked at all for most page loads. c) It loads the javascript after the page is rendered, so the user doesn't get a blank screen for several seconds while all of the javascript files are loaded. d) Moodle combines multiple javascript files, getting them in one request rather than 20. – Ray Morris Apr 13 '15 at 21:43
0
     <?php 
         //you have load $CFG , firstly check in config.php
         //after that print_r($CFG);
         //also you can use $CFG->wwwroot;

   require ('../config.php');
    require_once ($CFG->dirroot.'/login/lib.php');

//and then in your code:// after that
echo $OUTPUT->header(); ?>


<script src="<?php $CFG->wwwroot ?>/js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="<?php $CFG->wwwroot ?>js/jquery.validationEngine-en.js"    type="text/javascript" charset="utf-8"></script>
<script src="<?php $CFG->wwwroot ?>js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>
<?php $PAGE->requires->js(new moodle_url($CFG->wwwroot.'/blocks/your_block/script.js')); ?>
Avinash Maurya
  • 332
  • 3
  • 4