Aryan
Aryan

Reputation: 133

reponsive or device Conditionally load JavaScript file

I am looking to try this code for my project its not working for me

var js = document.createElement("script");

js.type = "text/javascript";

if (screen.width > 500)
{
    js.src = "js/jquery_computer.js";
}
else
{
    js.src = "js/mobile_version.js";
}

head.appendChild(js);

Conditionally load JavaScript file

not working link

http://itracktraining.com/sam.html

New Changes, same above link for demo

this seems not working i trying to call multiple jqueryfile and a function too :)

$(document).ready(function() {
                var width = $(document).width()
    var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");

js.type = "text/javascript";

if (width > 800)
{
    js.src = "js/jquery.slimscroll.min.js";
    js.src = "js/jquery.fullPage.js";
    js.src = "js/examples.js";
    $('#fullpage').fullpage({
                anchors: ['firstPage', 'secondPage', '3rdPage'],
                sectionsColor: ['#C63D0F', '#1BBC9B', '#7E8F7C'],
                css3: true
            });
}
else
{
    js.src = "js/mobile_version.js";
}

head.appendChild(js);

});

Upvotes: 0

Views: 39

Answers (1)

OptimusCrime
OptimusCrime

Reputation: 14863

In your code, the element head is not defined. You need to add the line:

var head = document.getElementsByTagName('head')[0];

At the beginning of your script.

Also, it looks like you are missing the screen variable. You can swap screen.width with window.innerWidth.

Complete, working example at jsfiddle.net/syLzb4yL.


Answer to edited question can be found here.

Upvotes: 1

Related Questions