DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • jQuery vs. Angular: Common Differences You Must Know
  • CSS3 Transitions vs. jQuery Animate: Performance
  • Better Scaffolding with jQuery - Part I
  • How to Call Rest API by Using jQuery AJAX in Spring Boot? [Video]

Trending

  • Advancing DSLs in the Age of GenAI
  • Top Load Balancing Algorithms: Choosing the Right Strategy
  • MCP Client Agent: Architecture and Implementation
  • Migrating Traditional Workloads From Classic Compute to Serverless Compute on Databricks
  1. DZone
  2. Coding
  3. Frameworks
  4. Load Scripts Dynamically With jQuery

Load Scripts Dynamically With jQuery

By 
Paul Underwood user avatar
Paul Underwood
·
Jun. 04, 14 · Interview
Likes (0)
Comment
Save
Tweet
Share
17.1K Views

Join the DZone community and get the full member experience.

Join For Free

A common tactic to help speed up your website is to use a technique called lazy loading which means that instead of loading everything your page needs at the start it will only load resources as and when it needs them.

For example you can lazy load images so you can start the page off only with the images you need to view the page correctly, then other images that are out of view you won't need to load straight away. As the user scrolls down the page you can then search to see if the images are about to come into view and lazy load the images when they are needed.

You can do the same with other resources such as JavaScript or CSS files, you can make sure you only load in the script as and when they need them to be used.

An example of this I have used in the past is loading Disqus comments on the click event of a button, this jQuery code will then load in the Disqus Javascript file and initialise the Disqus code on the selected div.

$j=jQuery.noConflict();

$j(document).ready(function() {
	$j('.showDisqus').on('click', function(){   // click event of the show comments button
		var disqus_shortname = 'enter_your_disqus_user_name';  // Enter your disqus user name

                // ajax request to load the disqus javascript
		$j.ajax({
	         type: "GET",
	         url: "http://" + disqus_shortname + ".disqus.com/embed.js",
	         dataType: "script",
	         cache: true
	     });

	        $j(this).fadeOut();  // remove the show comments button
	});
});

Ajax Method

As you can see from the code above we have a click event of the .showDisqus button, inside this using the jQuery method .ajax() which is making a GET request for the script of embedding Disqus into your application.

The ajax method is normally used to make basic http requests to a server side script and return the output of the script. On this occasion we are making a GET request and setting the dataType to be a script. This tells jQuery to treat the return as if we are including a new JavaScript file, this will disable browser caching on the script by adding a timestamp parameter to the end of the script.

If you would like to enable caching of the script then you need to make sure you include a cache: true parameter.

$.ajax({
    type: "GET",
    url: "http://test_script.js",
    dataType: "script",
    cache: true
});

Get Script Method

Another option to get the script via GET ajax is to use the method getScript() this is simply a wrapper for the above ajax method.

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

This allows you to reduce the amount of code you are writing by simply using this method.

$.getScript( "http://test_script.js" )
  .done(function( script, textStatus ) {
    alert('Successfully loaded script');
  })
  .fail(function( jqxhr, settings, exception ) {
    alert('Failed to load script');
});

The problem with using getScript() is that it will never cache the script as it will always add the timestamp querystring to the end of the JavaScript file. As the ajax() method allows you to choose if you cache the script or not it is better to use this method when loading in a script that will not change.

JQuery

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • jQuery vs. Angular: Common Differences You Must Know
  • CSS3 Transitions vs. jQuery Animate: Performance
  • Better Scaffolding with jQuery - Part I
  • How to Call Rest API by Using jQuery AJAX in Spring Boot? [Video]

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: