2016-08-30 10 views
1

mir eine Javascript-Funktion, die angeblich beim Laden der Seite komplett aufzurufen (wie JQuery der Funktion) heren, wie es aussieht:JavaScript-Funktion nicht auf Last aufgerufen wird

<script> 
var ready = function(fn) { 

    // Sanity check 
    if (typeof fn !== 'function') return; 

    // If document is already loaded, run method 
    if (document.readyState === 'complete') { 
     return fn(); 
    } 

    // Otherwise, wait until document is loaded 
    // The document has finished loading and the document has been parsed but sub-resources such as images, 
    //stylesheets and frames are still loading. The state indicates that the DOMContentLoaded event has been fired. 
    document.addEventListener('complete', fn, false); 
}; 

ready(function() { 
    alert(lang); 
    Load(@Model.Language); //<--this is what I want called 

    }); 
</script> 

------->MVC Stuff<------- 

function Load(lang) { 


switch (lang) { 
    case 'Other': 
     BuildBox("text/text"); 
    case 'CSharp': 
     BuildBox("text/x-csharp"); 
     break; 

} 

Wenn ich den Haltepunkt festgelegt auf die Zuordnung aus dem Modell, wir treffen es. Allerdings geschieht nichts anderes jemals (einschließlich der Alert-Box Ich bin nicht sicher, warum es nicht die Funktion vollständig von der Last der Ausführung

+0

Sie wollen window.onload = function() {...} –

+0

@EmmanuelDelay Das können Sie nur für eine Funktion tun. OPs-Code sollte theoretisch mehrere Aufrufe von 'ready()' für verschiedene Codeblöcke zulassen, die beim Laden der Seite ausgeführt werden müssen. –

+1

Versuchen Sie 'window.addEventListener ('load',() => ...)' stattdessen. –

Antwort

0

Dies funktioniert:...

function ready(fn) { 

    // Sanity check 
    if (typeof fn !== 'function') return; 

    // If document is already loaded, run method 
    if (document.readyState === 'complete') { 
    fn(); 
    } 

    // Otherwise, wait until document is loaded 
    // The document has finished loading and the document has been parsed but sub-resources such as images, 
    //stylesheets and frames are still loading. The state indicates that the DOMContentLoaded event has been fired. 
    document.addEventListener('readystatechange', function() { 
    if (this.readyState === 'complete') fn(); 
    }, false); 
} 

ready(function() { 
    alert("loading complete"); 
}); 
0

Ich schlage vor, Sie dies zu nutzen

(function() { 
    var x = "Hello!!";  // I will invoke  myself 
})(); 

die Klammern();., nachdem die anonyme Funktion selbst die Funktion ruft Und Sie können Dokument bereit Veranstaltung wie diese impliment

document.addEventListener('DOMContentLoaded', function() { 
    // ... 
}); 
.