You are here: Home / Documentation / How To's / How to run JavaScript code on page load

How to run JavaScript code on page load

by nguyen — published Dec 17, 2013 05:19 PM, last modified Aug 16, 2016 10:50 AM
document ready function

Here is a simple example showing how to get your JavaScript code to load when the page ("document") is ready.

From

http://developer.plone.org/templates_css_and_javascripts/javascript.html?highlight=document%20ready

Here is some JavaScript that I want to have run when the document is ready:

(function (jQuery) {
        var $ = jQuery;

        function alerttest() {
                alert("Hello world");
        }

        $(document).ready(alerttest);

})(jQuery);

Go to the ZMI -> portal_skins -> custom folder and add a new File object.  Call it "mytest.js".

Paste the above code into its text box and press Save.

Register the new JavaScript file by going to the ZMI -> portal_javascripts, scroll all the way to the bottom of the page, and fill out these fields:

  • ID: mytest.js
  • Enabled: checked (yes)
  • Merging allowed: no
  • Caching allowed: no
Press the Add button.
(We do not allow merging or caching so that we can see the mytest.js file get sent to your browser on its own, not merged in with other JavaScript files and named something else.)

Now go to any page of the site and reload it.  When the page finishes reloading, an alert box containing the message "Hello world" should pop up.

 

Navigation