Thursday, 12 January 2012

Javascript code to reload css files and js scripts and MySQL commands to disable constraints

I found this snippet of jQuery JavaScript on StackOverflow and it has been really useful. It reloads the stylesheets in a page without reloading the whole page itself. I just paste the code into Firebug and run it and it works its magic.

var queryString = '?reload=' + new Date().getTime();
$('link[rel="stylesheet"]').each(function () {
    this.href = this.href.replace(/\?.*|$/, queryString);
});

I tried to write something similar for Javascript where it reloads the <script> elements in the page but it was buggy. I think the script is double loaded into the page rather than replaced and I think this means it only really works for simple scripts that us mere mortals write but when you try to reload something complex like jQuery with all its handlers it goes a little funny. Here's the broken code anyway and I've set it to only look for and load mysimplescript.js only.

var queryString = '?reload=' + new Date().getTime();
$('head script').each(function(){
    if(/mysimplescript\.js/.test(this.src))
        $.getScript(this.src.replace(/\?.*|$/, queryString));
});

And another thing that really useful when you're dealing with tables with foreign key constraints and you're trying to reload them and it's giving you "MySQL constraint fails" errors - you can temporarily switch off constraint checking:


SET foreign_key_checks = 0;
INSERT INTO tableB SELECT * FROM tableA;
SET foreign_key_checks = 1;

But don't get too used to doing that hack. Constraints are put there for a reason.

No comments:

Post a Comment