Include Function in JavaScript

Here, a include function to JavaScript like PHP.

Good for conditional includes.

Using:

if(have_money==true)  {
 include("girs.js");
} else if(i_am_very_rich==true) {
 include("more_more_girls.js");
}else if(i_am_inteligent==true){
 include("no_girls_back_to_work.js");
}

Add this function to your code:

function include(arquivo){
//By Fabrício Magri e Micox
//http://elmicox.blogspot.com/2006/12/include-em-javascript.html
 var novo = document.createElement('script');
 novo.setAttribute('type', 'text/javascript');
 novo.setAttribute('src', arquivo);
 document.getElementsByTagName('head')[0].appendChild(novo);
 //apos a linha acima o navegador inicia o carregamento do arquivo
 //portanto aguarde um pouco até o navegador baixá-lo. :)
}

Tested sucessful in Internet Explorer 6.0, Firefox 2.0 and Opera 8.5.

Edit 02/08/07: A include_once function can be viewed here.

Bugs and comments? Just comment :) Bye.

Portuguese original version and comments.

7 comments:

  1. You have a problem in this script.

    function include(file_path){
    //By Anônimo and Micox - http://elmicoxcodes.blogspot.com
    var novo = document.createElement("script");
    novo.setAttribute('type', 'text/javascript');
    novo.setAttribute('src', file_path);
    document.getElementsByTagName('body')[0].appendChild(novo);
    //after this the browser start file loading
    //so wait for a moment, while browser working :)
    }

    <script> causes a Javascript Error, use script only for create the element.

    Sorry for my English.

    ReplyDelete
  2. Thanks anieto2K.
    Fabrício (Anônimo) alerts me in original post.

    Now is ok!
    Thanks!

    ReplyDelete
  3. Cool blog! Congratulations, guy. Good ini.. initiative (é assim?)! Subscribed!

    ReplyDelete
  4. The problem with they way your using it that the included script won't get parsed untill the current script is finished being parsed. here is a better solution for realtime inclusion.

    http://www.exit12.org/archives/12

    ReplyDelete
  5. Thanks anonymous. Very good.

    ReplyDelete
  6. careful tumbles subdebates circulated outright oakland bidding religion tide agood regulative
    servimundos melifermuly

    ReplyDelete
  7. needagreed sharon corporate impaired tangible sustainable parliament cinema ecological lessee ethic
    servimundos melifermuly

    ReplyDelete