2009-12-02 5 views
0

나는 거대한 JavaScript 성능 전문가가 아니다. 간단히 궁금해서 다음 코드를 더 작게 만들 수 있습니까? 그것을 포장하거나 압축하는 것과는 달리, 쓰여지는 방식으로 말입니다.JavaScript 코드 개선

(function() { 
    var jq = document.createElement('script'); 
    var an = document.createElement('script'); 
    var cm = document.createElement('script'); 
    var ga = document.createElement('script'); 
    var domain = 'http://example.com/'; 

    jq.src = domain + 'jquery.1.3.2.js'; 
    an.src = domain + 'jquery.alphanumeric.js'; 
    cm.src = domain + 'common.js'; 
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; 
    ga.setAttribute('async', 'true'); 

    document.documentElement.firstChild.appendChild(jq); 
    document.documentElement.firstChild.appendChild(cm); 
    document.documentElement.firstChild.appendChild(an); 
    document.documentElement.firstChild.appendChild(ga); 
})(); 

건배!

답변

1
'https:' == document.location.protocol ? 'https://ssl' : 'http://www' 

이 될 수 있습니다 : 문자열로

오히려 요소를 만드는 대신 비표준 자바 스크립트를 갈 의향이 아니라면, 내가 볼 수있는 유일한 개선의
'http' + 'https:'==document.location.protocol ? 's://ssl' : '://www' 

하지만, 실제 HTML 요소 , 문서 .innerHTML에 추가하십시오.

+0

흥미로운 VAR의 또는 모든 DOM 지침을 결합하는 방법이 있다면 단순히 궁금해서 내가 추측 : 희망이 수행 또는 async 속성을 필요로하지 않는 스크립트 (추가하거나 제거하는 것을 간단하게 그렇지 않다면 :) – James

7

작성 방법이 간결하고 성능은 관련이 없습니다. 그러나 컴팩트, 재사용 가능한 방법으로 그것을 쓰기 :

function appendScript(url, async) { 
    var el = document.createElement('script'), 
     root = document.documentElement; 
    el.async = async; 
    el.src = url; 
    // avoid an IE6 bug by using insertBefore (http://bugs.jquery.com/ticket/2709) 
    root.insertBefore(el, root.firstChild); 
} 


appendScript('http://example.com/js/jquery.1.3.2.js', false); 
appendScript('http://example.com/js/jquery.alphanumeric.js', false); 
appendScript('http://example.com/js/common.js', false); 
appendScript(('https:' == document.location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js'), true); 
+0

+1하지만 도메인에 대한 변수를 사용하는 것이 가치가있을 수도 있습니다 – Pool

+0

확실히 도메인을 변수로 지정하려고합니다.이 리팩터는 유연성이 부족합니다. – artlung

+0

확실히? 축제가 말했듯이, "가치있을"수도 있습니다. 제 생각에는 간단한 해결책으로 만난이 간단한 문제입니다. 도메인을 변수로 만들면 (비록 작지만) 복잡성이 추가되고 실제로는 이점이 없으므로 성능이 저하됩니다 (몇 바이트의 대역폭 절약). –

1
var child1 = document.documentElement.firstChild; 
child1.appendChild(jq); 
child1.appendChild(cm); 
child1.appendChild(an); 
child1.appendChild(ga); 
0

당신이 방법은 덜 반복하게하는 addScriptElement() 함수를 만들 수 있습니다.

0

나는이 '팽창',하지만 그냥 내가 그것을 얼마나 공유을 downvoted 얻을 것이다 확신 :

function addElements(objlist) { 
    // One or many 
    objlist = [].concat(objlist); 

    while(objlist.length > 0) { 
     var current = objlist.pop(); 

     var node = document.createElement(current.element || 'div'); 
     for(attr in current.attributes) 
      node.setAttribute(attr, current.attributes[attr]); 

     if(current.parent) 
      current.parent.appandChild(node); 
    } 
} 
:

첫째, 나는 매우 확장 될 것 같은 함수를 정의합니다

그런 다음,이 기능을 사용하려면

addElements([ 
    { 
     parent: document.documentElement.firstChild, 
     element: 'script', 
     attributes: { 
      src: 'http://example.com/jquery.1.3.2.js' 
     } 
    }, 
    { 
     parent: document.documentElement.firstChild, 
     element: 'script', 
     attributes: { 
      src: 'http://example.com/jquery.alphanumeric.js' 
     } 
    }, 
    { 
     parent: document.documentElement.firstChild, 
     element: 'script', 
     attributes: { 
      src: 'http://example.com/common.js' 
     } 
    }, 
    { 
     parent: document.documentElement.firstChild, 
     element: 'script', 
     attributes: { 
      src: ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js', 
      async: true 
     } 
    } 
]); 

을 나는 '전원 기능'을 부르는 그. 매우 읽기 쉽고 반복이 있더라도 권력으로 표현됩니다.

당신은 객체의 생성을 자동화 할 수 :

var elements = [ 
    'jquery.1.3.2.js', 
    'jquery.alphanumeric.js', 
    'common.js', 
    ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js' 
]; 

for(var i=0; i<4; ++i) { 
    elements[i] = { 
     element: 'script', 
     parent: document.documentElement.firstChild, 
     attributes: { 
      src: 'http://example.com/' + elements[i] 
     } 
    }; 
} 

elements[3].attributes.async = true; 

addElements(elements); 
+1

나는 downvote하지 않을거야,하지만 왜 몇 라인에서 할 수있는 무언가를 위해 많은 문제가 있습니까? –

+0

'힘'을 위해서. 나는 '모든 것'을 할 수있는 기능을 일반화하고 작성하는 것을 좋아합니다. 이 특별한 경우에는 나쁜 예가 될 수도 있지만, 그런 방법을 쓰고 공유하고 싶습니다. – LiraNuna

+0

공유하는 것이 좋습니다. 귀하의 첫 번째 라인에서 귀하의 포기와 함께, 당신은 아래쪽 투표를하지 않습니다. 분명히 나에게서 : P –

0

좋아, 여기에 나의 기회입니다. 현재 많은 돈을 절약하고 있는지 확신 할 수 없지만 example.com에 더 많은 자산으로 끝나면 속도가 빨라질 것입니다.

(function(){ 
    var scripts = ['jquery.1.3.2', 'jquery.alphanumeric', 'common'], 
     head  = document.documentElement.firstChild, 
     domain  = 'http://example.com/', 
     add_script = function(url, async){ 
      var script = document.createElement('script'); 
      script.src = url; 
      if(async === true) script.setAttribute('async', 'true'); 
      head.appendChild(script); 
     }; 

    for(script in scripts) add_script(domain + scripts[script] + '.js'); 

    add_script(('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js', true); 
})(); 
0

하나의 접근법이 있습니다. ..

({ 
    DOMAIN : 'http://example.com/', 
    SCRIPTS : [ {file:'jquery.1.3.2.js'}, 
      {file:'jquery.alphanumeric.js'}, 
      {file:'common.js'}, 
      {file: ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js' 
       , async: 'true'} ], 
    init: function() { 
     for (var i in this.SCRIPTS) { 
      var script = this.SCRIPTS[i]; 
      var sc = document.createElement('script'); 
      sc.src = (script.file.match(/^http/gi)) ? sc.src = script.file : sc.src = this.DOMAIN + script.file; 
      if (typeof script.async !== 'undefined') { 
       sc.setAttribute('async', script.async); 
      } 
      document.documentElement.firstChild.appendChild(sc); 
     } 

    } 
}).init();