2

In my actual project, the users have the option to click a button in order to enter in an "edit mode" for their websites. After clicking the button, I have to download several JS and CSS files and I was doing it using the following code:

//Start edition mode
(function(){
    $.get('/helpers/edit/v/edit.php',function(data){
        $(data).appendTo('body');
        var css = '/helpers/edit/css/edit.css';
        $.get(css,function(data){
            $('<link/>')
                .attr({
                    'rel':'stylesheet',
                    'href':css
                }).appendTo('head');
            $("body").trigger("editReady");
        });
    });
})();

It works fine but now I need to insert more JS and CSS files and if I just keep nesting jquery get requests the code will become ugly and hard to mantain, which I want to avoid and shows me that this is probably not the best way to accomplish the task.

I also tried to use Yep Nope (which I'm already using in other parts of the project) inside the first get request but it seems not to work (I receive no error messages but it just doesn't work).

Does anyone have an idea of how to do this in a way that doesn't get so ugly and, mainly, is easy to mantain (considering that I have to trigger an event when all the JS/CSS are properly included)?

Thanks in advance!

5
  • There's no duplication as I'm not looking for an alternative to Yep Nope. Commented Sep 4, 2012 at 19:01
  • in your above code you are not using yepnope, your problem can be caused false chmod rights or any other issue, do you not get an error in your console, how do you want to remove the css when you dont need it anymore? a request in q request? why not include the css in the php file? Commented Sep 4, 2012 at 19:05
  • I know I'm not using Yep Nope. As I said: It doesn't work here. And chmod rights are set correctly. Commented Sep 4, 2012 at 19:09
  • it should work - or you did something wrong Commented Sep 4, 2012 at 19:10
  • I also think it should work but... Regarding to your other questions: I receive no errors in my console, I have no reason to remove the css later and I don't use css inside php files. I surely could just load it in the head of the file but it's just a snippet and there's no head in it. Commented Sep 4, 2012 at 19:14

3 Answers 3

1

I had a similar issue loading JSON from multiple sources recently. I modified that code and came up with this. The gist of it is to loop through get requests to your various URL's and then trigger your "editReady" event when the number of requests completed is equal to the number of URL's in the data_urls array (i = data_urls.length).

I originally wrote this in CoffeeScript so it's possible that I messed up a bracket or something somewhere...

function() {
  var data_urls = ['/helpers/edit/v/edit.php', '/helpers/edit/css/edit.css'];
  var i = 0;
  var _i, _len;
  for (_i = 0, _len = data_urls.length; _i < _len; _i++) {
    $.get(data_urls[i], function(data) {
      if (data_urls[i].match(/\.php/).length > 0) {
        $(data).appendTo('body');
      } else if (data_urls[i].match(/\.css/).length > 0) {
      $('<link/>')
        .attr({
          'rel':'stylesheet',
          'href':css
        }).appendTo('head');
      }
      i += 1;
      if (i == data_urls.length) {
        $("body").trigger("editReady");
      }
    });
  }
} 
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a script loader like head.js http://headjs.com/

Seems require.js fits your needs: http://requirejs.org/

Also mentioned: LabJS http://labjs.com/ and YepNope http://yepnopejs.com/

Alternatives to YepNope and LabJS

YepNope seems to be very easy, there are the functions injectJs()and injectCss

yepnope.injectJs("jquery.js", ...
yepnope.injectCss("print.css", ...

4 Comments

I'm already using a script loader, which is the only one that solves all the matters I have in my application. Unfortunately, it doesn't solve this one... Thanks anyway!
Because it would limit the solution to the use of Yep Nope, which is not necessary. I want to find a solution and it doesn't need to use Yep Nope.
It doesn't limit the use to jquery. If you have a solution using pure js it is absolutely welcome!
I don't want to make it more difficult, I just want to find a solution for my problem! I don't care if the solution relies or not on jquery (but for personal experience, I believe it probably will and I totally agree with your last comment) and I don't care if it relies on Yep Nope or not. The main difference between limiting the answer to the users of jquery or the users of Yep Nope (which I'm not doing anyway) is the number of users of both.
1

I guess you can create an array of css and js file path and load it on iterating them i.e.

$.get('/helpers/edit/v/edit.php',function(data){
    $(data).appendTo('body');
    var css = ['mycss1.css','mycss2.css','mycss3.css'];
    $.each(css,function(index, elem){
       $('<link/>')
            .attr({
                'rel':'stylesheet',
                'href':elem
         }).appendTo('head');
    });

    var js = ['myjs1.js','myjs2.js','myjs3.js'];
    $.each(js,function(index, elem){
       $('<script></script>')
            .attr({
                'type':'text/javascript',
                'src':elem
         }).appendTo('head');
    });

    $("body").trigger("editReady");

});

Hope this will help.

6 Comments

I could be mistaken, but I do not believe your solution will wait until all of the requests have been completed to trigger the editReady event.
@niiru, why you are not believing? Is there any mistake in my code?
you could use the success method
@DanielRuf, there is no success method available in $.get. So please tell me where would be the best position for it.
This would be a nice solution if it wasn't for the point raised by @niiru. It would trigger the event much before the scripts were properly loaded.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.