0

I have loads of code that most need to be loaded BEFORE the other piece of code in order for it to work correctly. In order for me to achieve this I have multiple scripts over and over again. Is there a way I can clean some of this up? I will try and give examples:

//This needs to load first to add class
<script>
$(function(){
if (typeof(global_Current_ProductCode) !="undefined")
    {
        if ($('#pt494').length == 0 )
            {   $('font[class="text colors_text"]:eq(0)').closest('table').addClass('thePrices'); }    
    } 
});
</script>

//This needs to load 2nd because it has to add the class first before it does this
<script>
$(function(){
if (typeof(global_Current_ProductCode) !="undefined")
    {
        if ($('#pt490').length == 0 )
            {   $('table[class="thePrices"]:eq(0)').closest('table').before($('font[class="productnamecolorLARGE colors_productname"]:eq(0)').addClass('toptitle'));}
    } 
});
</script>

There is so much more code similar to this, there has got to be a way to throw it all under the same IF statement?

ToddN
  • 2,901
  • 14
  • 56
  • 96
  • 2
    Mmm, just putting them into the same `$(function())` underneath each other (or even underneath each other in the same if statement) should be enough. Or am I misunderstanding your question? – Pekka Jun 16 '11 at 21:02
  • No its a very basic question based on my limited knowledge of the DOM tree and if-statements =p – ToddN Jun 16 '11 at 21:06

2 Answers2

2

I'm not sure I understand your question. Code blocks written in sequence aren't executed simultaneously. Thus, you could consolidate your code like so:

<script>
$(function(){
if (typeof(global_Current_ProductCode) !="undefined")
    {
        if ($('#pt494').length == 0 )
        {   
            $('font[class="text colors_text"]:eq(0)').closest('table').addClass('thePrices'); 
        }   
        if ($('#pt490').length == 0) {
            $('table[class="thePrices"]:eq(0)').closest('table').before($('font[class="productnamecolorLARGE colors_productname"]:eq(0)').addClass('toptitle'));
        } 
    } 
});
</script>
Christopher Armstrong
  • 7,907
  • 2
  • 26
  • 28
  • Right, I need them to go one after another, after another, almost like in order based on my scripts I have now..this appears it could work I will do more testing and get back, thank you. – ToddN Jun 16 '11 at 21:08
  • Yep, you will get sequential execution (one after another) with the above. – Christopher Armstrong Jun 16 '11 at 21:13
0

Short of designing your own framework there isn't much you can do other than try to write cleaner code in the future. In my experience I generally consolidate all html injection stuff into a single function and call it before anything else.

You can also separate functions out to $(document).ready() and $(window).load. Window load will occur after document ready, but this is definitely not a be all end all solution for messy code.

MoarCodePlz
  • 5,086
  • 2
  • 25
  • 31