0

So I'm stuck behind this problem

I'm using AJAX to refresh my website and when I also need to add scripts to my newly loaded div. Foe this I'm using this piece of code

$.getScript('scripts/shBrushJava.js');
$.getScript('scripts/shCore.js');
setTimeout(function(){
    $(".left-content").load(document.location.hash.substr(1));
}, 10);

Sometimes this works and sometimes not as shown on pictures below

This is the working 2 pictures (Website and Firebug console) enter image description here enter image description here

These are the images from the time it's not working (95%) enter image description here enter image description here

As you can see, when the JS is not loaded properly, they are shown in console. How to fix this?

Hans
  • 752
  • 1
  • 15
  • 29

1 Answers1

0

As mentioned, ajax is asynchronous. So you are not guaranteed that the script files is loaded at any given time. You've set a timeout for 10 milliseconds. Some times, the files may have been loaded and parsed, sometimes not.

Here is an example on how you can guarantee that the scripts are loaded, but there is a tons of third party libraries available for this already. For example RequireJS.

Simple example:

var getAllScripts = function (scripts, callback) {
        var i, count = scripts.length;
        // Start loading all files
        for (i = 0; i < scripts.length; i += 1) {
            $.getScript(scripts[i], function () {
                // When loaded, decrease count
                count -= 1;
                // If all is loaded, call the callbacl
                if (count === 0) {
                    callback();
                }
            });
        };
    };

getAllScripts([
        'scripts/shBrushJava.js',
        'scripts/shCore.js'
    ],
    function () {
        // Here all files is loaded, do your magic here
        alert('All is loaded');
    }
);

Here is a fiddle to try it out

Or you can just put:

<script src="scripts/shCore.js" type="text/javascript"></script>
<script src="scripts/shBrushJava.js" type="text/javascript"></script>

In your <head> in your html. Then it's guaranteed to be loaded in the whole <body>.

  • i cant put them in head. I'm loading the part in ajax and then using
    . Brush is a thing in javascript and it wont open
    – Hans Apr 18 '14 at 22:55