Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6

Thread: Loading jQuery

  1. #1
    New Coder
    Join Date
    Jul 2009
    Posts
    68
    Thanks
    1
    Thanked 1 Time in 1 Post

    Loading jQuery

    Hi, I am trying to build an embeddable widget, so that a user can embed a short piece of javascript on their site and it will track where users click.

    My code for the HTML page is:
    Code:
    <script src="http://www.google.com/jsapi" type="text/javascript"></script>
    <script type="text/javascript">
            google.load("jquery", "1.3");
    </script>
    <script src="clickmap.js" type="text/javascript"></script>
    <script type="text/javascript">$(function() { $(document).saveClicks(); });</script>
    I am trying to shorten it down so I can load the jquery and clickmap.js through one file like this:
    Code:
    <script type="text/javascript" src="initial.js"></script>
    The clickmap.js code is:
    (
    Code:
    function($) {
    alert('HELLO');
    $.fn.saveClicks = function() {
        jQuery(this).bind('mousedown.clickmap', function(evt) {
            jQuery.post('clickmap.php', {  
                x:evt.pageX,  
                y:evt.pageY,  
                l:escape(document.location.pathname)
            });
        });
    };
    
    })(jQuery);
    I am able to load clickmap.js as the alert works but everything after that does not. I believe it may have something to do with loading the jQuery through google.load. When I load the jQuery through google.load without using inital.js the code will execute as it should, but when I load it like this:

    Code:
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
    Then the code will not execute.

    Code for initial.js:
    Code:
    (function () {
    
        var scriptName = "initial.js"; //name of this script, used to get reference to own tag
        var jQuery; //noconflict reference to jquery
        var jqueryPath = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
        var jqueryVersion = "1.8.3";
        var scriptTag; //reference to the html script tag
    
        var allScripts = document.getElementsByTagName('script');
        var targetScripts = [];
        for (var i in allScripts) {
            var name = allScripts[i].src
            if(name && name.indexOf(scriptName) > 0)
                targetScripts.push(allScripts[i]);
        }
    
        scriptTag = targetScripts[targetScripts.length - 1];
    
        function loadScript(src, onLoad) {
            var script_tag = document.createElement('script');
            script_tag.setAttribute("type", "text/javascript");
            script_tag.setAttribute("src", src);
    
            if (script_tag.readyState) {
                script_tag.onreadystatechange = function () {
                    if (this.readyState == 'complete' || this.readyState == 'loaded') {
                        onLoad();
                    }
                };
            } else {
                script_tag.onload = onLoad;
            }
            (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
        }
    
        if (window.jQuery === undefined || window.jQuery.fn.jquery !== jqueryVersion) {
            loadScript(jqueryPath, initjQuery);
        } else {
            initjQuery();
        }
    
        function initjQuery() {
            jQuery = window.jQuery.noConflict(true);
            main();
        }
    
        function main() {
            jQuery(document).ready(function ($) {
                loadScript("clickmap.js", function() { /* loaded */ });
            });
            
        }
    
    })();
    Could anyone help me fix this please?

  • #2
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,726
    Thanks
    6
    Thanked 1,013 Times in 986 Posts
    If you are using jQuery already then use $.getScript() to load scripts asynchronously, for the most consistent functionality.
    Also, is the JS console saying anything?

  • #3
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Try this:

    PHP Code:
    <script type="text/javascript">window.jQuery || document.write('<scr' 'ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/scr' 'ipt>');</script>
    <script type="text/javascript" src="clickmap.js"></script> 
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #4
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Loading the script via $.getScript() or any asynchronous method is still not guaranteed that the script has been executed. From $.getScript documentation: "The callback is fired once the script has been loaded but not necessarily executed.".

    Loading the script synchronously (as what my suggestion does) guarantees the script is loaded and executed before proceeding to the next script tag.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #5
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,726
    Thanks
    6
    Thanked 1,013 Times in 986 Posts
    I was referring to this:
    Code:
    function main() {
        jQuery(document).ready(function ($) {
            loadScript("clickmap.js", function() { /* loaded */ });
        });   
    }
    Instead of that custom loadScript function one can use getScript if jQuery is present anyway.

    And the OP is doing it with a method similar to the one I’m usually using when I include jQuery:
    Code:
    function include(file, callback) {
    	var head = document.getElementsByTagName('head')[0];
    	var script = document.createElement('script');
    	script.type	= 'text/javascript';
    	script.src = file;
    	script.onload = script.onreadystatechange = function() {
    		if (callback) {callback();}
    		// prevent memory leak in IE
    		head.removeChild(script);
    		script.onload = null;
    	};
    	head.appendChild(script);
    }
    if(typeof jQuery==="undefined"){
    	include('path/to/jquery.min.js', runScript);
    }
    else {
    	runScript();
    }
    function runScript() {
    	$('html').addClass('jsenabled');
    	$.ajaxSetup({cache: true});
    	$(function() {
    		// custom functions here, using $.getScript to include other JS files
    	});
    }
    In the HTML I’m doing this:
    Code:
    <script type="text/javascript" src="[path to jQuery CDN here]"></script>
    <script type="text/javascript" src="functions.js"></script>
    functions.js contains the above code. The CDN script can even be left out because the JS in functions.js checks whether jQuery is present and if not, includes it from a local copy. I’ve never had problems using getScript in this set-up. And no need for crappy document.write().

  • #6
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Shouldn't you check for:

    Code:
    script.readyState === 'complete' || script.readyState === 'loaded'
    before executing the callback?
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •