Question

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?

Was it helpful?

Solution

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>

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top