Import javascript in javascript

Discussion in 'JavaScript' started by XandroZ, Apr 17, 2007.

  1. #1
    I know that I can import an css file in other css file with @import
    Ex: @import "style.css";

    Can I do something like this in javascript, import a javascript in other javascript ;
     
    XandroZ, Apr 17, 2007 IP
  2. Aragorn

    Aragorn Peon

    Messages:
    1,491
    Likes Received:
    72
    Best Answers:
    1
    Trophy Points:
    0
    #2
    You can use
    document.write("<script type='text/javascript' src='test.js'></scr"+"ipt>");
    Code (markup):
    Note that you should split the closing script tag into two parts.

    Or else you can use the DOM model to acheive the same
    
    // Create the Script Object
    var script = document.createElement('script');
    script.src = 'server.js';
    script.type = 'text/javascript';
    script.defer = true;
    script.id = 'scriptID'; // This will help us in referencing the object later for removal
    // Insert the created object to the html head element
    var head = document.getElementsByTagName('head').item(0);
    head.appendChild(script);
    Code (markup):
    Similary you can also remove a script object
    
    var head = document.getElementsByTagName('head').item(0);
    var old = document.getElementById('scriptID');
    if (old) head.removeChild(old);
    
    Code (markup):
     
    Aragorn, Apr 18, 2007 IP
    ajsa52 likes this.