4

For my backend I want to automatically load javascript files when it detects certain elements. Here is an example:

if($('.wysiwyg').length>0) {
     include('javascript/ckeditor/ckeditor.js');
     $(".wysiwyg").ckeditor();
}

But when I execute the code I get $(".wysiwyg").ckeditor is not a function because it seems the browser is still loading or parsing the javascript file that was included on the line before. If I put an alert popup right before the function it does work because it "pauzes" the script I guess and gives it time to load the file.

Is there a way I can know when the file is actually loaded so that the followed code can be executed?

EDIT: Seems that I asked this question a bit too soon. I found out the e.onload property for a callback function that solved this problem. This is my function now if others might stumble upon the same problem:

function include(script, callback) {
    var e = document.createElement('script');
    e.onload = callback;
    e.src = script;
    e.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e);
}


if($('.wysiwyg').length>0) {
    include('javascript/ckeditor/ckeditor.js', function() {
        $(".wysiwyg").ckeditor();
    });
}
4
  • what is "include"? server or client? Commented Jul 11, 2011 at 7:44
  • include is a client side function that creates a script element and appends it to the <head> Commented Jul 11, 2011 at 7:49
  • @mplungjan explained in updated question. Commented Jul 11, 2011 at 7:56
  • possible duplicate of Loading javascript files automatically with sequential callbacks Commented Jul 11, 2011 at 7:58

5 Answers 5

3

Why not use the built in ajax-based getScript?
It also has a callback mechanism that allows you to execute some code only after the required script has been succesfully loaded :

function include(script,callback){
    $.getScript(script, function() {
        if(typeof callback == 'function')
        callback.apply({},arguments);
    });
}

and then you can use it in such a manner:

if($('.wysiwyg').length>0) {
    include('javascript/ckeditor/ckeditor.js',function(){
        $(".wysiwyg").ckeditor();
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Did not know jQuery had this, thanks. Is there a big difference between getScript and my solution above? Because my include function also loads css files (removed that bit to reduce space in question).
well, it has almost the same result, but your solution appends an item (script or link or some other tag) to the dom and lets the dom interpret it, while my solution uses ajax and then evaluates the script. The only big difference is if you want to increase your dom (and leave traces of your scripts :P) or not
2

When you're using jQuery with promises you can use a modified version of the above code like so:

function include(srcURL) {
    var deferred = new $.Deferred();
    var e = document.createElement('script');
    e.onload = function () { deferred.resolve(); };
    e.src = srcURL;
    document.getElementsByTagName("head")[0].appendChild(e);
    return deferred.promise();
}

Then you can use the above code with a '$.when(include('someurl.js'))' call. This will let you have

  1. The global window context (which you need for CKEditor)
  2. The ability to defer executing other code until the when resolves
  3. A script that doesn't require a callback and a context for that to be passed because jQuery is handling that with the promises functionality it includes.

I hope this helps someone else who is looking for more than a callback, and multiple scripts to be loaded with jQuery's promises/deferred functionality.

2 Comments

This is a clever way to handle making sure the script or scripts are loaded and ready before try to making use of the functionality. Thanks!
But also see the jQuery getScript docs for a more straightforward implementation that also handles errors.
2

You can also try YepNope - a conditional javascript loader

yepnope is an asynchronous conditional resource loader that's super-fast, and allows you to load only the scripts that your users need.

Comments

0

You can do it this way

$(document).ready(function()
{
 if($('.wysiwyg').length>0) {
       $('head').append('<script language="javascript" src="javascript/ckeditor/ckeditor.js"></script>');
     $(".wysiwyg").ckeditor();
}

});

5 Comments

I did not have problems with the include function, that is a function that I already wrote and worked.
do u see that I have added method which will be executed when all elements are loaded?
Yes, but $(document).ready has no effect on the script that is loaded afterwards.
Look, you are searching for elements with the class .wysiwyg, and if they are not loaded your script won't be executed, so $(document).ready is jquery method which is executed when document is loaded, so when your document is loaded then search for .wysiwyg element will be executed and your script will work.
The .wysiwyg element already exists when the page is loaded. In my question I say I want to load specific javascript files when it detects a certain element.
0

Modernizr can do this for you. See this MetaFlood article: Use jQuery and Modernizr to load javascript conditionally, based on existence of DOM element.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.